为什么我们在原型继承中使用临时盒子?

Why do we use a temporary box in prototype inheritance?

下面的函数是 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 继承任何 属性,它不存在于它的原型中,如您所见,您没有调用 parent' s constructor 任何地方。

我创建了一个 fiddle 来解释这个 here

在第二个扩展函数中,当您调用 Parent 的 constructor Child.prototype = new Parent() 时,Parent 的所有属性都在 Parent 的原型以及所有其他原型将由 Child 继承;即它将全部进入 Child 的 prototype.

我也创建了一个 fiddle here 来解释这一点。