2011-02-09 98 views
2

比方說,我有一個函數/值的對象。我對基於調用行爲的重載感興趣。我可以用一個函數重載一個對象嗎?

例如,下面這段代碼演示了我想要做的事情。

var main_thing = { 
    initalized: false, 
    something: "Hallo, welt!", 
    something_else: [123,456,789], 
    load: { 
     sub1 : function() { 
      //Some stuff 
     }, 
     sub2 : function() { 
      //Some stuff 
     }, 
     all  : function() { 
      this.sub1(); 
      this.sub2(); 
     } 
    } 
    init: function() { 
     this.initalized=true; 
     this.something="Hello, world!"; 
     this.something_else = [0,0,0]; 
     this.load(); //I want this to call this.load.all() instead. 
    } 
} 

這個問題對我來說是main_thing.load被分配到一個對象,並呼籲main_thing.load.all()會調用該對象(()運營商)的內部功能。我能做些什麼來設置我的代碼,以便我可以使用main_thing.load作爲訪問對象,並且main_thing.load()執行一些代碼?或者至少,類似的行爲。

基本上,這與其他語言中不需要調用main_thing.constructor()的默認構造函數類似。

如果這是不可能的,請詳細解釋一下。

+0

你描述聽起來像一個構造函數,但你將其形容爲超載。我在這裏看不到任何重載函數。 – 2011-02-09 15:21:50

+0

函數是對象,因此您可以將「子函數」設置爲函數的屬性。在`main_thing.load.all`中順便說一下`this`並不是指`main_thing`,而是指向`main_thing.load`。 – 2011-02-09 15:23:57

+0

我可能會誤解 - 但如果你添加一個var loadfunctions = {sub1:function(){..},sub2 ...},然後重寫你的負載到類似load:function(switch){if(!開關){loadfunctions.all; }其他...等 – Prescott 2011-02-09 15:28:45

回答

3

湯姆一樣塗說,函數是對象,並且可以有屬性...

var main_thing = { 

    // load will be set to the result of this anonymous function 
    // which is a function with 2 extra properties set for the other functions   
    load: function() { 
     // create what will be the load() function and store in "all" 
     var all = function() { 

       // When the function is actually executed these will have been assigned 
       all.load1(); 
       all.load2(); 
      }; 

     // set 2 properties for sub load functions 
     all.load1 = function() {}; 
     all.load2 = function() {}; 

     // return our function 
     return all; 
    }() 
} 

main_thing.load(); 
// or 
main_thing.load.load1(); 
main_thing.load.load2(); 
1

因爲函數對象只是對象,所以引用函數的對象屬性與引用普通對象的對象屬性之間沒有真正的區別。因此,「負載」只是外部對象的屬性。

你可以做的是初始化「初始化」功能,裏面的「負荷」的對象以使得其功能必須通過一個封閉訪問外部對象的引用:

init: function() { 
    // whatever ... 

    var main_thing = this; 
    this.load.sub1 = function() { 
    main_thing.foo = "bar"; 
    }; 
    this.load.sub2 = function() { 
    main_thing.somethingElse(); 
    } 
} 

現在,這些功能中的「負荷「子對象有權訪問該」main_thing「局部變量,它將引用外部對象。它們如何被調用並不重要。

另一種方法是在較新的瀏覽器中使用「bind()」工具,或者像Prototype of Functional這樣的庫提供。 (我個人只是偷綁定從Functional.js因爲它是一個乾淨的實施)。

init: function() { 
    // ... 

    this.load.sub1 = function() { 
    this.foo = "bar"; 
    } .bind(this); 

} 

這種做法保證了無論「SUB1」怎麼叫,它會永遠擁有this綁定到參考當它(「sub1」,即)被定義時可用的外部對象。

0

你不能像這樣重載JavaScript。 如果您main_thing.load功能,那麼你可以調用main_thing.load(),您也可以訪問內部的值,就像這樣:

main_thing.load.a = 7; 
main_thing.load.b = "text"; 
main_thing.load.foo = function(x,y){alert("Hello, world "+x+", "+y); }; 
main_thing.load.foo(main_thing.load.a,main_thing.load.b); 

它提醒「你好,世界7文本」。

但main_thing.load本身可以用來存儲一個函數,也可以用來存儲其他一些數據,但不能同時存儲。

相關問題