下面的函数是他的OO Javascript教程中使用的Derek Banas在youtube上使用的函数。
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
。
我创造了一个小提琴来解释这个here。
在第二个扩展函数中,当您调用Parent的constructor
Child.prototype = new Parent()
时,Parent
的所有属性,以及所有那些不存在的Child
属性都将由prototype
继承;即它将全部进入儿童的here。
我已经创建了一个小提琴qazxswpoi来解释这一点。