原型模式
2016-09-20 18:27
204 查看
原型模式主要是为了代码重用。问题在于在子类的指针指向父类的可重用数据时,应该怎么处理,因为共享意味着互相影响。子类修改了共享的数据,也会影响父类。所以这里需要用一个中间的,空白的函数作中继。这样不仅可以重用父类的代码和数据,还可以重写父类的的数据和方法而不影响父类。
function Parent(name){
this.name = name;
}
Parent.prototype.show = function(){
console.log(this.name + " from Parent");
}
function Children(name){
Parent.apply(this,arguments);
}
function F() {
}
F.prototype = Parent.prototype;
Children.prototype = new F();//new Parent()
Children.prototype.show = function(){
console.log(this.name + " from Children");
}
new Children('hi').show();
new Parent('hi').show();
重点是Children.prototype = new F();//new Parent()这一句,new Parent()也能达到这种效果,如果Parent函数是空函数,其实就等价于new F(),但是除了父类的原型外,父类函数里往往会有可供子类重用的代码,比如帮助子类初始化数据的代码 this.name = name;使得子类
4000
可以以 Parent.apply(this,arguments);这样的形式重用。而如果Parent不为空,那么new Parent()作为原型的时候,this.name
= name生成的变量空间就会被浪费。所以利用一个空的F函数作为中继会比较好。
function Parent(name){
this.name = name;
}
Parent.prototype.show = function(){
console.log(this.name + " from Parent");
}
function Children(name){
Parent.apply(this,arguments);
}
function F() {
}
F.prototype = Parent.prototype;
Children.prototype = new F();//new Parent()
Children.prototype.show = function(){
console.log(this.name + " from Children");
}
new Children('hi').show();
new Parent('hi').show();
重点是Children.prototype = new F();//new Parent()这一句,new Parent()也能达到这种效果,如果Parent函数是空函数,其实就等价于new F(),但是除了父类的原型外,父类函数里往往会有可供子类重用的代码,比如帮助子类初始化数据的代码 this.name = name;使得子类
4000
可以以 Parent.apply(this,arguments);这样的形式重用。而如果Parent不为空,那么new Parent()作为原型的时候,this.name
= name生成的变量空间就会被浪费。所以利用一个空的F函数作为中继会比较好。
相关文章推荐
- sql输入单引号总显示错误 为什么
- 实用SQL语句大全
- 分布式锁的介绍及使用方案
- BZOJ2393: Cirno的完美算数教室 容斥原理
- curl 取得HTTP返回的状态码
- easy ui in action 两个月总结
- Android一点 修改jar的内容
- Zxing扫码流程梳理
- 完美世界2017C++游戏开发笔试编程题
- ssh_pam认证
- hbase快速入门-- java api 操作
- 51单片机之LCD1602的驱动程序
- 操作集合的工具类:Collections
- 支付架构
- 无线安全专题_攻击篇--干扰通信
- 为什么要线程同步,说出线程同步的几种方法
- [较复杂的数位DP] HDU 4507 吉哥系列故事——恨7不成妻
- LinkedHashMap实现类和IdentityHashMap实现类
- php string去掉emoji表情
- Asp.Net Web应用程序无法拖放控件