簡體   English   中英

在構造函數中分配原型

[英]Assigning prototype inside constructor

我有這個代碼:

var MyClass = function(b) {
    this.a = b;
    this.getA = function() {
        return that.a;
    }
}

var SecondClass = function(b) {
    this.prototype = new MyClass(b);
    this.getB = function() {
        return 6;
    }
}

var a = new SecondClass(2);
console.log(a.getA());

輸出告訴我a沒有名為getA()的方法

我假設在SecondClass的構造函數中執行this.prototype = new MyClass()會導致它從MyClass的inhert方法?

我確信有更好的方法可以做到這一點,但我試圖理解prototype關鍵字的行為。

prototype構造函數的特殊屬性,而不是實例的特性

當您使用new Func()調用構造函數時,引擎將創建一個從Func.prototype繼承的新對象,然后在構造函數內部設置this以引用新對象。

因此,除了this.prototype只是一個普通的屬性,繼承已經發生在賦值發生時。

由於您沒有為MyClass.prototype分配任何方法,因此您不必在此處對原型繼承執行任何操作。 您所要做的就是使用.call [MDN]MyClass應用於新創建的實例:

var SecondClass = function(b) {
    MyClass.call(this, b);
    this.getB = function() {
        return 6;
    }
};

但是,您應該將實例共享的所有方法添加到原型中 ,然后讓SecondClass每個實例繼承它。 這就是完整設置的樣子:

var MyClass = function(b) {
    this.a = b;
}
MyClass.prototype.getA = function() {
    return this.a;
};

var SecondClass = function(b) {
    // call parent constructor (like 'super()' in other languages)
    MyClass.call(this, b);
}
// Setup inheritance - add 'MyClass.prototype' to the prototype chain
SecondClass.prototype = Object.create(MyClass.prototype);
SecondClass.prototype.getB = function() {
    return 6;
};

var a = new SecondClass(2);
console.log(a.getA());

所有這一切在ES6中都會變得更容易

名為“prototype”的屬性僅對作為函數的對象感興趣。 為構造函數中的“prototype”屬性賦值不起作用(在本例中); 重要的是構造函數本身的“原型”屬性。

SecondClass.prototype = new MyClass();

或者其他的東西。 構造函數的原型對象在構造的所有實例之間共享,因此通過構造函數參數改變原型也沒有多大意義。

你可以做的另一件事是從“SecondClass”中調用“MyClass”構造函數:

function SecondClass(b) {
  MyClass.call(this, b);
  this.getB = function() {
    return 6;
  };
}

這將具有使效果this是在構建new SecondClass()調用的“MyClass的”構造進行裝飾。 它不會真的是繼承,但你會得到一個“getA”函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM