使用「點」的原型名字裏面可以說我有這個類:在JavaScript
function classA(n){
this.name = n
}
classA.prototype.getName = function(){
return this.name
}
var x = new classA('john')
console.log(x.getName())
我的問題是:我可以組一個命名空間內的多個方法?所以我想這樣做:
var x = new classA('john')
console.log(x.CONSTANT.getName())
所以我想調用一些方法爲x.someMethod()等,作爲x.CONSTANT.otherMethod()
PS:我在尋找一個跨瀏覽器的方法。綁定不適用於Safari和IE9。
我喜歡這種方法,但我不喜歡你需要在CONSTANT json中定義所有方法的事實。如果你有很多他們的代碼將不得不縮進,一切看起來很亂。也許我可以讓json中的otherMethod()指向外部定義的真正方法。 – RaduC 2012-03-01 10:32:45
「你需要定義CONSTANT json中的所有方法」並非強制性的。你可以寫'MyClass.prototype.CONSTANT = {}; MyClass.prototype.CONSTANT.otherMethod = function(){...}' – kirilloid 2012-03-01 11:55:33
thx ....看起來乾淨...缺點是爲ie/safari我需要檢查Function.prototype.bind並實施它,如果它不存在 – RaduC 2012-03-01 14:00:03