2016-10-31 36 views
0

對不起轉儲問題我是js的新手。我想覆蓋D「class」中的f2()函數。但由於某種原因,福克斯福克斯告訴我:「遞歸太多」。你能指點我發生遞歸的地方,以及如何使這段代碼按預期工作?JS繼承例子:遞歸太多

var B = function() { 
}; 
B.prototype.f2 = function (x) { 
    return 2 * x; 
}; 

var C = function() { 
    B.call(this); 
}; 

var D = function() { 
    C.call(this); 
}; 

D.prototype.f2 = function (x) { 
    return C.prototype.f2.call(this, x) * 7; 
}; 

inherit(B, C); 
inherit(C, D); 

function inherit(Child, Parent) { 
    Child.prototype = Object.create(Parent.prototype); 
    Child.prototype.constructor = Child; 
} 

var d = new D(); 
console.log(d.f2(3)); 
+2

我很好奇,爲什麼你正在學習ES5原型鏈,以便專心(基於這個和至少一個ot她回答你的問題)。上面的'inherit'函數已經過時了。從ES2015開始,這裏有一個簡單明瞭的聲明語法,並且可以爲尚不支持它的較舊環境轉換語法。在這種語法中,它很容易理解。因此,研究這種過時的做法似乎是非最優的。 –

+0

*(不是我的dv ...)* –

+0

非常感謝你,你的回答非常有幫助!我參加了js中關於古典oop模式的培訓,並且我們被要求以ES5和ES2015兩種方式實施它。但我明白你在說什麼,這是有道理的,並讓我的世界更加清晰。 –

回答

4

兩個問題:

  1. 您需要在嘗試將屬性添加到他們之前設置了XYZ.prototype對象。由於您的inherit函數創建它們,您必須確保您按照正確的順序進行操作。

  2. 您的inherit調用中有父母和子女的順序落後。它是inherit(child, parent),而不是inherit(parent, child)

var B = function() { 
 
}; 
 
B.prototype.f2 = function (x) { 
 
    return 2 * x; 
 
}; 
 

 
var C = function() { 
 
    B.call(this); 
 
}; 
 
inherit(C, B);   // *** Moved and updated 
 

 
var D = function() { 
 
    C.call(this); 
 
}; 
 
inherit(D, C);   // *** Moved and updated 
 

 
D.prototype.f2 = function (x) { 
 
    return C.prototype.f2.call(this, x) * 7; 
 
}; 
 

 
function inherit(Child, Parent) { 
 
    Child.prototype = Object.create(Parent.prototype); 
 
    Child.prototype.constructor = Child; 
 
} 
 

 
var d = new D(); 
 
console.log(d.f2(3));

的ES2015版本進行比較:

class B { 
 
    f2(x) { 
 
    return 2 * x; 
 
    } 
 
} 
 

 
class C extends B { 
 
} 
 

 
class D extends C { 
 
    f2(x) { 
 
    return super.f2(x) * 7; 
 
    } 
 
} 
 

 
const d = new D(); 
 
console.log(d.f2(3));