以下功能是youtube上的Derek Banas在OO Javascript教程上使用的功能。
function extend(Child, Parent){
var Temp = function(){};
Temp.prototype = Parent.prototype;
Child.prototype = new Temp();
Child.prototype.constructor = Child;
}
为什么我们必须使用Temp原型?我们为什么不能这样做:
function extend(Child, Parent){
Child.prototype = new Parent();
Child.prototype.constructor = Child;
}
好。这两个功能的主要区别在于行
Temp.prototype = Parent.prototype;
和 Child.prototype = new Parent();
第一个extend
功能仅显示原型继承。该Child
不会继承的任何财产Parent
,这是不是有在它的原型,你可以看到,你是不是调用父类的constructor
任何地方。
在第二个extend函数中,当您调用Parent时constructor
Child.prototype = new Parent()
,Parent
Parent原型中存在的的所有属性,以及所有不存在的属性都将被继承Child
;也就是说,这一切都将进入孩子的prototype
。
我在这里也创建了一个小提琴来解释这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句