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
所以原型对象的整体修改,要在其构造函数的调用之前完成。
建议继续学习:
- 软件架构模式的种类 (阅读:2809)
- 让生活变简单的简单网站 (阅读:2207)
- 状态模式和策略模式的比较 (阅读:1766)
- 关于经营模式 (阅读:1589)
- JavaScript Creating Objects Other Pattern (阅读:1569)
- 聊聊设计模式(4):装饰模式 (阅读:1266)
- Python创建单例模式的三种方式 (阅读:1146)
- [译]Go开发中一些有用的模式 (阅读:778)
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:simaopig 来源: 小小子,simaopig
- 标签: 动态原型 模式
- 发布时间:2010-06-02 22:56:39
- [12] Python连接 MySQL 数据库的超时问
- [11] 产品设计之QQ邮箱登录页与淘宝登录页
- [11] 手机客户端交互适配设计之我见
- [10] 谈谈Facebook的聊天系统架构
- [10] 一个 VLA (可变长度数组)的实现
- [9] 没有比解决瓶颈更高效的事情了
- [9] PDC 2010:C#与Visual Bas
- [9] 四年前的今天,我开始找工作
- [9] 一句话crontab实现防ssh暴力破解
- [8] Linux 安装pptp vpn clien