您的位置:首页 > 其它

原型模式

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函数作为中继会比较好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: