2012-03-01 29 views
3

使用「點」的原型名字裏面可以說我有這個類:在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。

回答

3

你可以做到這一點,例如,通過bind。 Google es5 shim用於在瀏覽器中實現綁定,但本機不支持。

function MyClass(name) { 
    this.name = name; 
    this.CONSTANT.otherMethod = this.CONSTANT.otherMethod.bind(this); 
} 
MyClass.prototype.CONSTANT = { 
    otherMethod: function() { 
     alert(this.name); 
    } 
}; 
+0

我喜歡這種方法,但我不喜歡你需要在CONSTANT json中定義所有方法的事實。如果你有很多他們的代碼將不得不縮進,一切看起來很亂。也許我可以讓json中的otherMethod()指向外部定義的真正方法。 – RaduC 2012-03-01 10:32:45

+0

「你需要定義CONSTANT json中的所有方法」並非強制性的。你可以寫'MyClass.prototype.CONSTANT = {}; MyClass.prototype.CONSTANT.otherMethod = function(){...}' – kirilloid 2012-03-01 11:55:33

+0

thx ....看起來乾淨...缺點是爲ie/safari我需要檢查Function.prototype.bind並實施它,如果它不存在 – RaduC 2012-03-01 14:00:03

1

據我所知常量只是一個屬性,它不能包含方法,你需要單獨的對象和使用方法有同樣的效果:

function A (id) { 

    this.id = id; 
    this.showId = function() { return this.id; } 
}; 

function B (a) { 

    this.a = a; 
    this.getA = function() { return this.a; } 
} 

var a = new A(12); 
var b = new B(a); 

b.getA().showId(); 

編輯: 您可以使用文本對象如下

function B (id) { 

    this.id = id; 
    this.CONSTANT = { otherMethod: function() { alert("..."); } }; 
    someMethod = function() { return this.id; } 
} 

但常量對象不能訪問B-對象的方法,

考慮一下@kirilloid這篇文章。

+0

一個對象的屬性本身可以是一個包含方法的對象(並且這個嵌套可以像所期望的那樣深)。查看其他答案。 – nnnnnn 2012-03-01 09:41:00

+0

@nnnnnn我更新了我的答案,無論如何,我認爲文字對象無法訪問其父方法,事實證明,你可以改變這一點,看看kirilloid的答案 – user544262772 2012-03-01 09:52:38

+0

是的,一個嵌套的對象無法通過某種'父'屬性或任何東西(因爲實際上嵌套對象實際上不屬於父對象,父對象只是持有對它們的引用),但是你可以用'.bind()'來解決它。 – nnnnnn 2012-03-01 10:30:08

0

你可以,但你必須小心,因爲它不會像你想象的那樣行事。該方法的this將是命名空間,而不是根對象。例如,在x.CONSTANT.getName()中,this對象將是x.CONSTANT,而不是x

下面是一些示例代碼,有點做什麼你問(或in jsfiddle):

function MyClass() {} 

MyClass.prototype.CONSTANT = { 
    getName: function() { 
     alert('Foo'); 
    } 
}; 


var c = new MyClass(); 
c.CONSTANT.getName(); 

爲了確保this是正確的,你需要做的更多。

-1

您可以使用getters/setters(讀取this article)來實現此目的。例如,你可以這樣定義它:

classA.prototype.__defineGetter__('CONSTANT', function() { 
    var that = this; 
    return { 
     getName: function() { 
      return that.name; 
     } 
    }; 
}); 

that持有對象的引用。它現在可以工作

x = new classA('test'); 
x.CONSTANT.getName(); 
// result - test