首页 > 技术文章 > 读书笔记-JavaScript高级程序设计(1)

adouwt 2018-07-05 10:45 原文

 

 

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

  

  

 

推荐阅读