2010-04-08 49 views
1

我在命名空間函數時引用期望的對象時遇到問題。在命名空間函數中引用期望的對象

這裏沒有問題:但我發現絆了一跤

obj.test = function() { 
    // this == obj 
} 

當我命名空間:

obj.namespace.test = function() { 
    // this == namespace 
} 

在後一個例子,我知道this引用namespace,但我想引用obj 。我該怎麼做?

回答

1

其他人提出了一些很好的建議。

我只是想添加你也可以使命名空間的一個函數,將返回一個變量指向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(); 
1

有沒有簡單的答案,但你有幾種選擇:

obj.namespace.test = function() { 
    return (function() { 
    // this == obj 
    }).apply(obj, Array.prototype.slice.call(arguments)); 
}; 

這將返回綁定到obj功能。不幸的是,如果obj被重新分配,這將不起作用,因爲它是一個實時參考。這是更強大:

obj.namespace.test = (function (obj) { 
    return function() { 
    return (function() { 
     // this == obj 
    }).apply(obj, Array.prototype.slice.call(arguments)); 
    }; 
}(obj)); 

正如你所看到的,這些都不是很乾淨。你可能會問自己爲什麼依靠this開始。使用對obj的正常引用顯然是最直接的方法。