为什么 JavaScript 继承是这样工作的

why javascript Inheritance work like this?

本文关键字:工作 JavaScript 继承 为什么      更新时间:2023-09-26

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

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;
}

谁能为我解释?

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

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