IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

JavaScript Dynamic Prototype Pattern

小小子,simaopig 2010-06-02 22:56:39 累计浏览 2,608 次
本机暂存

    熟悉其它面向对象语言的人们在看待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. translateZ() (2026-06-25 21:18:56)
  2. translateY() (2026-06-25 21:17:56)
  3. translateX() (2026-06-25 21:16:01)

查看更多 前端 文章 →

建议继续学习

  1. JQuery实现Excel表格呈现 (累计阅读 48,349)
  2. 深入理解Javascript之执行上下文(Execution Context) (累计阅读 18,404)
  3. 从输入 URL 到页面加载完成的过程中都发生了什么事情? (累计阅读 15,933)
  4. 图片动态局部毛玻璃模糊效果的实现 (累计阅读 14,848)
  5. 天朝第二代身份证号码的验证机制 (累计阅读 14,761)
  6. HTML 5 的data-* 自定义属性 (累计阅读 14,349)
  7. 分享一个JQUERY颜色选择插件 (累计阅读 14,223)
  8. 什么是全栈工程师? (累计阅读 14,038)
  9. 快速排序(Quicksort)的Javascript实现 (累计阅读 11,735)
  10. 7 天打造前端性能监控系统 (累计阅读 11,187)