您现在的位置是:首页 > 文章详情

读书笔记-JavaScript高级程序设计(1)

日期:2018-07-04点击:349

 

 

1.组合继承 (JavaScript 中最常用的继承模式 )

(position: page168)

(书中定义了两个变量名 SuperType   SubType  乍一看 感觉不太能区分,我将改为 a b ,更加明显区分开来这是两个东西。)

 

function a(name){ this.name = name; this.colors = ["red", "blue", "green"]; } a.prototype.sayName = function(){ alert(this.name);
}
function b(name, age){ //继承属性 a.call(this, name); this.age = age; } //继承方法 b.prototype = new a();
b.prototype.constructor
= b;
b.prototype.sayAge
= function(){ alert(this.age); }; var instance1 = new b("Nicholas", 29);
instance1.colors.push(
"black");
alert(instance1.colors);
//"red,blue,green,black"

instance1.sayName(); //"Nicholas";

instance1.sayAge(); //29

var instance2 = new b("Greg", 27);
alert(instance2.colors);
//"red,blue,green"

instance2.sayName(); //"Greg";

instance2.sayAge(); //27

完成继承的思路:

使用原型链实现对原型属性和方法的继承, 使用构造函数来实现对实例属性的继承。


 

在这个例子中, a构造函数定义了两个属性: name colorsa的原型定义了一个方法 sayName()b构造函数在调用 a构造函数时传入了 name 参数,紧接着又定义了它自己的属性 age。然后,将 a的实例赋值给 b的原型,

然后又在该新原型上定义了方法 sayAge()。这样一来,就可以让两个不同的 b 实例既分别拥有自己属性——包colors 属性,又可以使用相同的方法了。 

 

2.寄生组合式继承 (实现基于类型继承的最有效方式 )

function object(o){ function F(){} F.prototype = o; return new F(); } function inheritPrototype(subType, superType){ var prototype = object(superType.prototype); //创建对象 prototype.constructor = subType; //增强对象 subType.prototype = prototype; //指定对象 } function a(name){ this.name = name; this.colors = ["red", "blue", "green"]; } a.prototype.sayName = function(){ alert(this.name); }; function b(name, age){ a.call(this, name); this.age = age; } inheritPrototype(b, a); b.prototype.sayAge = function(){ alert(this.age); }; // 调用 var instance1 = new b("Nicholas", 29); instance1.colors.push("black"); alert(instance1.colors); //"red,blue,green,black" instance1.sayName(); //"Nicholas"; instance1.sayAge(); //29 var instance2 = new b("Greg", 27); alert(instance2.colors); //"red,blue,green" instance2.sayName(); //"Greg"; instance2.sayAge(); //27 

 

原文链接:https://yq.aliyun.com/articles/612495
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章