簡體   English   中英

JavaScript類傳遞參數

[英]Javascript class passing parameters

我已經創建了幾個類,但是在類本身上從來沒有任何需要的參數。

以下代碼可以完美運行。

$(function()
{
   search.anotherFunction('a', 'b');
});

search = function()
{

   this.anotherFunction = function(param1, param2)
   {
      // do whatever
   };

   var public = { anotherFunction: anotherFunction }  

   return public;
}();

但是現在我想在search中傳遞參數,以避免將相同的參數傳遞給所有函數。

$(function()
{
   search('front/file.php').anotherFunction('a', 'b');
});

search = function(url)
{

   this.anotherFunction = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   this.anotherFunctionB = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var public = { anotherFunction: anotherFunction,
                  anotherFunctionB: anotherFunctionB }  

   return public;
}();

這不起作用,並且控制台輸出錯誤。

未捕獲的TypeError:對象不是函數

這意味着search不是函數,而是類名,因此無法接收參數?

首先,您建立“班”的方式不正確,並最終創建全局變量:調用您的匿名函數內部,因為你調用的方式, this將涉及全局對象*,所以this.anotherFunction = ...將創建一個稱為anotherFunction的全局變量,因為全局對象上的屬性是全局變量。

如果您想以最小的變化繼續使用當前模式,則不要在函數中使用this.xyz = ... ,而應使用var

var search = function()
{
   var anotherFunction = function(param1, param2)
   {
      // do whatever
   };

   var public = { anotherFunction: anotherFunction }  

   return public;
}();

另請注意,您沒有聲明search 成為“內隱全球性恐怖”的獵物; 我添加了一個var來聲明它。

如果您調用最外層函數,而是僅將函數分配給search變量,然后再調用它,則具有上述更改的第二個示例將起作用。

var search = function(url)
{

   var anotherFunction = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var anotherFunctionB = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var public = { anotherFunction: anotherFunction,
                  anotherFunctionB: anotherFunctionB }  

   return public;
}; // <== Note, no () here

現在search指向一個函數,我們可以這樣調用它:

var x = search("http://example.com");
x.anotherFunction(...); // Will have access to the URL

*為什么在調用匿名函數時, this引用全局對象? 因為你把它沒有做任何事情來設置this到別的東西,而你使用松散模式。 (我知道您使用的是寬松模式,因為如果您使用的是嚴格模式, this它將是undefined ,因此this.anotherFunction = ...將會失敗。)


旁注:我建議您停止使用public作為變量名,因為它是將來的保留字,並且至少從ES3開始使用。

您可以在此處使用JavaScript閉包。 查看以下方法:

search = function()
{
    return function (url) {
       this.anotherFunction = function(param1, param2)
       {
          // use here the 'url' parameter
       };

       this.anotherFunctionB = function(param1, param2)
       {
          // use here the 'url' parameter
       };

       var public = { anotherFunction: anotherFunction,
                      anotherFunctionB: anotherFunctionB }  

       return public;
    }
}();

search('front/file.php').anotherFunction('a', 'b');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM