[英]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.create
從ClassB
的prototyoe
繼承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 class
的prototype
屬性是不可配置的,因此你無法為它分配另一個對象。 您也可以在不改變configurable
到true
,一旦它已經被設置為false
。 唯一的選擇是在循環中復制成員函數。
您可以通過Object.getOwnPropertyDescriptor()
方法驗證這一點:
class ClassA{ } //configurable and writable is false console.log(Object.getOwnPropertyDescriptor(ClassA, "prototype"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.