簡體   English   中英

將原型B的所有方法和屬性分配到原型A中?

[英]Assign all methods and properties of prototype B into prototype A?

我有一個A類,它是B類的一個子集。它共享B類的許多屬性和方法。

但是A類缺乏實施。 所以我希望B類中的所有功能都進入A類。

ClassA.prototype = ClassB.prototype;

要么

ClassA.prototype += ClassB.prototype

但似乎我必須:

ClassA.prototype.methodA = ClassB.prototype.methodA
ClassA.prototype.methodB = ClassB.prototype.methodB
ClassA.prototype.methodC = ClassB.prototype.methodC
ClassA.prototype.methodD = ClassB.prototype.methodD

對於每一種方法和財產。 難道我無法一次將B中的實現放入A中嗎?

確實,你不能覆蓋通過class語法創建的函數的prototype屬性,因為它既是只讀的又是不可配置的。 如果您使用function語法而不是Fullstack Guy指出的話,您可以這樣做。

但是你可能想讓ClassA 擴展 ClassB

class ClassA extends ClassB {
    // ...
}

實例:

 class ClassB { methodA() { console.log("methodA"); } methodB() { console.log("methodB"); } methodC() { console.log("methodC"); } methodD() { console.log("methodD"); } } class ClassA extends ClassB { // ... } new ClassA().methodA(); 

但是,如果沒有,您可以使用循環復制所有方法:

for (const name of Object.getOwnPropertyNames(ClassB.prototype)) {
    const method = ClassB.prototype[name];
    if (typeof method === "function") {
        ClassA.prototype[name] = ClassB.prototype[name];
    }
}

實例:

 class ClassB { methodA() { console.log("methodA"); } methodB() { console.log("methodB"); } methodC() { console.log("methodC"); } methodD() { console.log("methodD"); } } class ClassA { // ... } for (const name of Object.getOwnPropertyNames(ClassB.prototype)) { const method = ClassB.prototype[name]; if (typeof method === "function") { ClassA.prototype[name] = ClassB.prototype[name]; } } new ClassA().methodA(); 

但請注意,如果ClassB是一個子類,那么方法中的super將繼續訪問ClassB的超類方法,它既不會無效,也不會訪問ClassA的超類方法。

您可以使用Object.createClassBprototyoe繼承ClassA的原型:

 function ClassB(){ } ClassB.prototype.methodA = function(){ console.log("methodA"); } function ClassA(){ //no implementation } //Make the prototype of Class A inherit from the ptottype of Class B ClassA.prototype = Object.create(ClassB.prototype); const classA = new ClassA(); classA.methodA(); 

上面是函數構造函數,如果你想使用ES6類,那么你只需要extend ClassB

 class ClassB{ methodA(){ console.log("methodA"); } } class ClassA extends ClassB{ } const classA = new ClassA(); classA.methodA(); // When you extend another class, the instance methods of super class are inherited // in the prototype property of the child class ClassA.prototype.methodA(); 

由於@TJ Crowder理所當然地說Object classprototype屬性是不可配置的,因此你無法為它分配另一個對象。 您也可以在不改變configurabletrue ,一旦它已經被設置為false 唯一的選擇是在循環中復制成員函數。

您可以通過Object.getOwnPropertyDescriptor()方法驗證這一點:

 class ClassA{ } //configurable and writable is false console.log(Object.getOwnPropertyDescriptor(ClassA, "prototype")); 

暫無
暫無

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

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