다른 사람들은 몇 가지 좋은 제안을했습니다.
그냥 네임 스페이스를 obj를 가리키는 변수와 원하는 멤버 함수를 가리키는 개체로 반환하는 함수를 추가 할 수도 있습니다.
예 :
// Note that "namespace" is a reserved word in JS for some reason,
// so you can't use it as a variable/function/etc name.
var myNamespace = function myNamespace(){
var that = this;
var test = function test(){
//in here use this.that to point to obj
alert(this.that.name);
};
return {that: that, test: test};
};
// Then create the obj:
var obj = { name: "Mr. Ahb Jeckt", myNamespace: myNamespace};
// Then you can just call the "namespace" and member function like this:
obj.myNamespace().test();
//Or, "initialize" the namespace and call it like so:
obj.myNamespace = obj.myNamespace();
obj.myNamespace.test();
obj.name = "Mrs Ahb Jeckt";
obj.myNamespace.test();
이 방법은 거기에 "네임 스페이스"자체 obj와 어떤 하드 코딩 된 참조가 있고, 나는 그것이 매우 깨끗 생각합니다.
obj가 "클래스"인 경우에도 작동합니다. obj를 객체 리터럴 대신 생성자로 만듭니다.
// Then create the obj:
var obj = function (name){
this.name = name || "unnamed";
this.myNamespace = myNamespace;
// Initialize the namespace, we can leave this out and just reference
// obj.myNamespace() each time as well
this.myNamespace = this.myNamespace();
};
// Then you can just call the "namespace" and member function like this:
var myObj = new obj("Mr Ahb Jeckt");
myObj.myNamespace.test();
var myObj2 = new obj("Mrs Ahb Jeckt");
myObj2.myNamespace.test();