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.
在我们的构造函数内部实现时,我们通过判断其原型链上的函数是否已经存在来决定是否为其原型对象设置方法,以便达到我们共享函数的目的(方法放在其原型对象上了)。
//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.
}
var person = new Person();
Person.prototype = {
constructor: Person,
name : "Nicholas",
age : 29,
job : "Software Engineer",
sayName : function () {
alert(this.name);
}
};
person.sayName(); //error
所以原型对象的整体修改,要在其构造函数的调用之前完成。
建议继续学习:
- 软件架构模式的种类 (阅读:3479)
- 让生活变简单的简单网站 (阅读:2797)
- Python创建单例模式的三种方式 (阅读:2454)
- 状态模式和策略模式的比较 (阅读:2367)
- 聊聊设计模式(4):装饰模式 (阅读:2352)
- JavaScript Creating Objects Other Pattern (阅读:2093)
- 关于经营模式 (阅读:2016)
- [译]Go开发中一些有用的模式 (阅读:1881)
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:simaopig 来源: 小小子,simaopig
- 标签: 动态原型 模式
- 发布时间:2010-06-02 22:56:39
-
[927] WordPress插件开发 -- 在插件使用 -
[126] 解决 nginx 反向代理网页首尾出现神秘字 -
[51] 如何保证一个程序在单台服务器上只有唯一实例( -
[50] 整理了一份招PHP高级工程师的面试题 -
[48] CloudSMS:免费匿名的云短信 -
[48] Innodb分表太多或者表分区太多,会导致内 -
[48] 用 Jquery 模拟 select -
[48] 全站换域名时利用nginx和javascri -
[48] 海量小文件存储 -
[46] ps 命令常见用法
