2011-05-27 48 views
0

我想要創建幾個對某個特定函數是本地的對象,但我希望另一個函數充當幫助者。幫助器功能的目的是減少重複代碼的數量(最終會隨着腳本的進展創建許多對象)。JavaScript對象

我'確定'我的腳本,確保它的工作原理,然後複製/粘貼下面。名爲'foo'的函數有效(有一個php文件未顯示用於jQuery/ajax調用)。不過,我希望ajax調用在getNode函數(幫助器函數)中,並且最好還在getNode中設置一個臨時對象。我的想法是,一個臨時對象可以從getNode傳遞給foo。

<script type="text/javascript"> 
    function Node() { 
     this.nodeId; 
     this.type; //can be used for diferent shapes, color cobinations, etc. 
     this.text; 
    } 

    function getNode(id){ 
     $.post("updateDB.php", send, function(theResponse){ 
      var responseArray = theResponse.split(','); 
      ....? 
    } 

    function foo(id){ 
     var centerNode = new Node(); 
     var send = 'id=' + id + '&action=getNode'; 
     $.post("updateDB.php", send, function(theResponse){ 
      var responseArray = theResponse.split(','); 
      centerNode.nodeId = responseArray[0]; 
      centerNode.type = responseArray[1]; 
      centerNode.text = responseArray[2];   
      alert('nodeId' + centerNode.nodeId); 
      alert('node type' + centerNode.type); 
      alert('node text' + centerNode.text); 
     });     
    } 
</script> 
</head> 
<body> 
<a onclick="foo(5)">test</a> 
</body> 

回答

1

一種方式是提供一個回調來getNode

function getNode(id, callback){ 
    $.post("updateDB.php", send, function(theResponse){ 
     var responseArray = theResponse.split(','); 
     var node = new Node(); 
     node.nodeId = responseArray[0]; 
     node.type = responseArray[1]; 
     node.text = responseArray[2];   
     callback(node); 
    }); 
} 

編輯: 「怎麼會foo是設置」

因此,在該示例中,foo將通過獲取節點對象並提醒其數據來響應click事件。這是我的理解。如果getNode被定義如上:

function foo(id) { 
    getNode(id, function(node) { 
    alert('nodeId' + node.nodeId); 
    alert('node type' + node.type); 
    alert('node text' + node.text); 
    } 
}); 
+0

謝謝克里斯。我對JavaScript非常陌生,所以我只是谷歌搜索'回調',看看我可以如何使用它。如何設置'富'? – 2011-05-28 00:22:40

+0

回調是JavaScript的真棒/可怕的功能。事實上你需要它們,因爲這種語言是異步的。在你調用'foo'的原始示例中,沒有'theResponse'數據。這還沒有被ajax post回調填充。在我的'getNode'函數版本中,我將ajax回調鏈接到'foo'回調函數中。這很難描述,所以我希望這一點很清楚。 – Chris 2011-05-28 01:41:52

0

好沸騰你的問題到要領(我想局部變量可用在不同的功能):

  1. 您可以通過對象的輔助函數。
  2. 您可以創建一個類並將兩個函數都放入其中,並使該函數局部變爲全局的類。

這些是我現在能想到的唯一方法。

JS類例如:

function ClassName(vars){ 
    //This is used to init the class and is called when you use var myClass = new ClassName(); 
    //example: this.varName = this.functionName(); 
    //Instead of using prototype (will see latter in this example) you could just define the function/vars in here like (which would make them private to this class): 
    //this.functionName = function(vars){}; 
} 

ClassName.prototype.functionName = function(vars){} //Out hear makes these var/functions publicly accessible 
ClassName.prototype.varName = 5; 

然後使用它:

var myClass = new ClassName(vars); 
myClass.functionName(vars); 

所以,把你的局部變量,並在構造函數中的輔助功能,使他們的私人和您的其他功能作爲原型使其可公開訪問。