2012-07-10 75 views
0

我無法弄清楚如何擁有一個正確接受參數的javascript函數。輸入到javascript函數

我可以得到完美的功能工作,如果我不使用的輸入參數,因爲我可以這樣做:

var x = MyFunction; 

但此刻我必須這樣做

var x = MyFunction(e); 

然後休息。

我試着通過後來設置輸入參數來解決這個問題,但我無法得到任何工作。我怎樣才能做到這一點?

http://jsfiddle.net/TxMmG/

var MyFunction = function() { 

    var otherResult = function() { 
     alert("Hi"); 
    }, 

     input, objToAlert = function() { 
      return input; 
     }; 

    return { 
     objToAlert: objToAlert, 
     input: input, 
     otherResult: otherResult 
    } 

}(); 


var e1 = "test"; 


//var y = MyFunction(e); //this does not work if i add a parameter to function - moment i put parenthesis i get problems 
var x = MyFunction; 
x.input = e1; //also cant set the input here 
x.objToAlert(); 
x.otherResult(); 

回答

2

你把()函數定義後,因此函數被調用,MyFunction實際上是由函數,不函數本身返回的對象。

這樣做:

var MyFunction = function() { 
    // ... 
}; // No() here 
0

的問題是,你的函數返回一個對象。因此你正在將一個對象分配給var y。你不能把對象看作一個函數。