javascript 高级程序设计 十二

1、组合使用原型模式和构造函数模式:

由于原型模式创建对象也有它的局限性------有智慧的人就把原型模式和构造函数模式进行了组合。


function Person(name, age, job){//用构造函数模式来定义每个实例化对象中特有的属性 this.name = name; this.age = age; this.job = job; this.friends = ['Shelby', 'Court']; } Person.prototype = {//用原型模式来定义共享属性和方法 constructor: Person,//当重写了prototype后,prototype中的constructor就不会指向方法对象而是指向构造函数,所以我们要重新定义constructor属性使其指向Person对象。 sayName: function(){ alert(this.name); } } var person1 = new Person('Tom', 12, 'engineer'); var person2 = new Person('Kim', 10, worker); person1.friends.push('Nini'); alert(person1.friends);//Shelby, Court, Nini alert(person2.frnends);//Shelby, Court

 当然,JS还有很多创建对象的模式:动态原型模式(和构造函数模式很像)、寄生构造函数模式、稳妥构造函数模式等,我就不在赘述了。

如果感兴趣就请看《JavaScript高级程序设计 (第三版)》的第六章。。。

继承开一个小头

  实现原型链的基本模式

function SuperType(){
  this.prototype = true;
}
SuperType.prototype.getSuperValue = function(){
  alert(this.prototype);
}
function SubType (){
  this.prototype = false;
}
//继承
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
  alert(this.prototype);
}
var subInstance = new SubType();
subInstance.getSuperValue();