首页 > JavaScript > JavaScript Dynamic Prototype Pattern
2010四月26

JavaScript Dynamic Prototype Pattern

熟悉其它面向对象语言的人们在看待JS混合模式时总是感觉很奇怪,将构造函数和原型模式分开写让他们感觉很不爽。这里略微抱怨一下,众口总是难调。十全九美其实挺好。

那么为了让这一部分人爽起来,就有必要来介绍一下动态原型模式。

The dynamic prototype pattern seeks to solve this problem by encapsulating all
of the information within the constructor while maintaining the benefits of using both a constructor
and a prototype by initializing the prototype inside the constructor, but only if it is needed.

在我们的构造函数内部实现时,我们通过判断其原型链上的函数是否已经存在来决定是否为其原型对象设置方法,以便达到我们共享函数的目的(方法放在其原型对象上了)。

function Person(name, age, job){
                   
    //properties
    this.name = name;
    this.age = age;
    this.job = job;
   
    //methods
    if (typeof this.sayName != "function"){
   
        Person.prototype.sayName = function(){
            alert(this.name);
        };
       
    }
}
                   
var person = new Person("Nicholas", 29, "Software Engineer");
person.sayName();

在上面的代码中,我们首先判断对象是否已经拥有sayName方法,如果尚未拥有,我们为其原型对象赋予sayName属性。而这一步骤只在构造函数第一次被调用时实现。原型上的方法又会被其所有实例化对象共享,所以一切都很完美。

但是这里我们需要注意,在使用动态原型模式时,原型对象不能使用对象直接量来表示。因为虽然可以在任意时间为原型对象增加属性或方法,所有实例化对象都会通过反射来共享这些属性和方法。但是却不能覆盖整个原型对象以期待获取同样的效果。

The __proto__ pointer is assigned when the constructor is called, so changing the prototype to a
different object severs the tie between the constructor and the original prototype. Remember: the
instance has a pointer to only the prototype, not to the constructor.

function Person(){
}
                   
var person = new Person();
       
Person.prototype = {
    constructor: Person,
    name : "Nicholas",
    age : 29,
    job : "Software Engineer",
    sayName : function () {
        alert(this.name);
    }
};
                   
person.sayName();   //error

所以原型对象的整体修改,要在其构造函数的调用之前完成。

function Person(){
}
       
Person.prototype = {
    constructor: Person,
    name : "Nicholas",
    age : 29,
    job : "Software Engineer",
    sayName : function () {
        alert(this.name);
    }
};
var person = new Person();                  
person.sayName(); //"Nicholas"

文章作者:simaopig
本文地址:http://www.xiaoxiaozi.com/2010/04/26/1753/
版权所有 © 转载时必须以链接形式注明作者和原始出处!

One Response to “JavaScript Dynamic Prototype Pattern”

  1. #1 风也飘泊 回复 | 引用 Post:2010-04-30 15:29

    玩得越来越高深 ….曲高和寡呀 :shock:

    [回复]

发表评论

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)