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

问题描述 投票:1回答:1

下面的函数是他的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;

}
javascript inheritance prototypal-inheritance
1个回答
1
投票

好。两个函数的主要区别在于行

Temp.prototype = Parent.prototype;

Child.prototype = new Parent();

第一个extend函数仅显示原型继承。 Child不会继承Parent中的任何属性,这在其原型中不存在,你可以看到,你没有在任何地方调用父母的constructor

我创造了一个小提琴来解释这个here

在第二个扩展函数中,当您调用Parent的constructor Child.prototype = new Parent()时,Parent的所有属性,以及所有那些不存在的Child属性都将由prototype继承;即它将全部进入儿童的here

我已经创建了一个小提琴qazxswpoi来解释这一点。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.