【问题标题】:why javascript Inheritance work like this?为什么javascript继承会这样工作?
【发布时间】:2013-11-13 16:27:25
【问题描述】:

当我们使用 javascript Inheritance,并且子类从其父类继承时,我们总是这样做:

var klass = function(){ this.init.apply(this, arguments)};

if(parent) {
    var subclass = function(){};
    subclass.prototype = parent.prototype;
    klass.prototype = new subclass;
}

上面的代码来自《Javascript Web Application》,我很困惑它和下面有什么区别:

var klass = function(){ this.init.apply(this, arguments)};
if(parent) {
    klass.prototype = parent.prototype;
}

谁能帮我解释一下?

【问题讨论】:

  • klass.prototype = parent.prototype; 表示这两个函数现在共享同一个 prototype 对象。所以对klass.prototype 的添加将出现在parent.prototype 上。这显然是不可取的。

标签: javascript class inheritance


【解决方案1】:
var klass = function(){ this.init.apply(this, arguments)};
if(parent) {
    klass.prototype = parent.prototype;
}

在这段代码中,klass.prototype 被设置为同一个对象 parent.prototype 是(parent 和 klass 共享同一个原型)。因此,如果你这样做:

klass.prototype.myFunc = function() {}

var p = new parent();
p.myFunc // myFunc will be available on all instances of parent (which is bad!)

更糟糕的是,如果你有

parent.prototype.myFunc = function() { console.log('I parent'); };

而你尝试重写 klass 的 myFunc 函数:

klass.prototype.myFunc = function() { console.log('I child'); };

var p = new parent()
parent.myFunc() // I child

您可以了解为什么共享原型是一个坏主意。

【讨论】:

  • 作为你的描述,如果我添加 parent.prototype.myFunc = function() { console.log('I parent'); };但是我没有在child中重写函数myFunc,那么klass就不能调用klass.myFunc,对吗?
  • @Frankjs 错了。 klass 可以访问在 klass.prototype 上定义的任何函数,该函数与 parent.prototype 相同,因此它可以访问 parent.prototype.myFunc。 klass 没有从父类继承方法,它使用它是因为它们有些组合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 2014-03-18
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多