技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> JavaScript Dynamic Prototype Pattern

JavaScript Dynamic Prototype Pattern

浏览:1703次  出处信息

    熟悉其它面向对象语言的人们在看待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

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

建议继续学习:

  1. 软件架构模式的种类    (阅读:2794)
  2. 让生活变简单的简单网站    (阅读:2193)
  3. 状态模式和策略模式的比较    (阅读:1754)
  4. 关于经营模式    (阅读:1579)
  5. JavaScript Creating Objects Other Pattern    (阅读:1560)
  6. 聊聊设计模式(4):装饰模式    (阅读:1242)
  7. Python创建单例模式的三种方式    (阅读:1129)
  8. [译]Go开发中一些有用的模式    (阅读:746)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1