2013-08-16 176 views
1

如何在Javascript中將值傳遞給超類構造函數。Javascript中的原型繼承

在下面的代碼片段

(function wrapper() { 
var id = 0; 

window.TestClass = TestClass; 

function TestClass() { 
    id++; 
    this.name = 'name_' + id; 
    function privateFunc() { 
     console.log(name); 
    } 
    function publicFunc() { 
     privateFunc(); 
    } 

    this.publicFunc = publicFunc; 
} 

function TestString() { 
    this.getName = function() { 
     console.log("***" + this.name + "****************"); 
    } 
} 

TestClass.prototype = new TestString(); 
})(); 

我如何通過值將TestString構造?目前,超類方法正在使用'this'關鍵字使用值。有沒有辦法直接將值傳遞給超類的構造函數。另外,我想看一個擴展String的簡單例子。這會讓很多事情神祕化。

+1

我建議不要使用'TestClass.prototype =新的TestString();'來建立繼承:http://stackoverflow.com/q/17392857/218196 –

+0

看起來你將使用「私有變量「,那麼原型繼承不起作用(其他對象屬性也不起作用) – Esailija

+0

@ Esailija ..可以請您詳細說明。這裏有一些幫助的例子。謝謝。 – Gopal

回答

2

您可以在TestClass()的構造函數中使用以下代碼。

TestString.apply(this, arguments); 

這將調用帶有新對象作爲其上下文的構造函數。

但是請注意,使用TestClass.prototype = new TestString();建立[[Prototype]]鏈將已經調用了構造函數一次。

jsFiddle

我想查看延伸String的簡單示例。

您可以增加其prototype屬性。

String.prototype.endsWidth = function(str) { 
    return this.slice(-str.length) === str; 
}; 
+0

@ alex ..感謝您的快速響應。你可以請檢查這個小提琴http://jsfiddle.net/gCwZD/1/我已經評論了原型部分,仍然,它的工作!這怎麼可能? – Gopal

+0

@Gopal:因爲你沒有添加任何東西到'TestString.prototype',因此無論你是否設置它都沒關係。我建議閱讀https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript以更好地瞭解'prototype'屬性實際是什麼。 –

+0

@ FelixKling ..我在這裏看你的答案http://stackoverflow.com/questions/17392857/benefits-of-using-object-create-for-inheritance感謝您的好解釋。但是,我在這裏沒有收到一件事。爲什麼我強制要求超類構造函數。例如,你可以檢查這個小提琴http://jsfiddle.net/AvVG2/1/? – Gopal