您的位置:首页 > Web前端 > JavaScript

javascript中的原型与继承2--构造函数窃取Constructor Stealing

2017-11-27 11:06 281 查看
Constructor Stealing,又叫object masquerading(对象伪装)或者classical inheritance。这种方法可以解决原型链中的问题。

Professional JavaScript  for Web Developers中的原话是:

The basic idea is quite simple:call the supertype constructor form within the subtype constructor.Keeping in mind that functions are simply
objects that excute code in a particular context,the apply() and call() methods can be used to execute a constructor  on the newly created object。

下面是例子:

//例子来源于Professional JavaScript  for Web Developers,third edition ,Volume 1的207页

function SuperType() {
this.colors=['red','blue','green'];

}

function SubType() {
//inherit from SuperType
SuperType.call(this);

}

var instance1=new SubType();

instance1.colors.push('black');

console.log(instance1.colors);//[ 'red', 'blue', 'green', 'black' ]

var instance2=new SubType();

console.log(instance2.colors);//[ 'red', 'blue', 'green']

the SuperType constructor is called in the context of the newly created instance of SubType.

不管是使用apply还是call都可以传递参数,就不说了。

但是这种方式实现的继承也有问题,看下面

SuperType.prototype.shuohua=function () {
console.log('说话');

}

instance2.shuohua();//TypeError: instance2.shuohua is not a function

什么问题呢,就是 methods must be defined inside the constructor,so there is no function reuse.Furthermore,methods defined on the supertype's prototype
are not accessible on the subtype,so all types can use only the constructor pattern.

参考文献:

Professional JavaScript  for Web Developers
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 继承
相关文章推荐