2015-02-08 77 views
0
$("#foo").on("click", function() { 
    amountItems.speek('heey') 
}) 

var amountItems = (function(el) { 
    // var el = el; 
    return { 
     speek: function() { 
      alert(el) 
     } 
    } 
}()) 

這是我第一次嘗試使用模塊模式。基本上當foo被點擊時,我想要調用amountItems函數內的speek方法,並且我想將字符串'heey'傳遞給方法,所以當點擊foo時它應該提醒'heey'。最初我想傳遞像$(「#foo」)。text()這樣的東西,但是我得到'undefined'。將參數傳遞給模塊模式函數時得到未定義

你可以告訴我如何使用jQuery對象時,它傳遞到這種類型的函數?

回答

1

您只是在el的參數錯誤的地方。這工作:

$("#foo").on("click", function() { 
    amountItems.speek('heey') 
}) 

var amountItems = (function() { 
    return { 
     speek: function(el) { 
      alert(el); 
     } 
    } 
}()) 

- 編輯 -

以防萬一你想知道整個範圍/私有變量的事情是如何工作的:

$("#foo").on("click", function() { 
    amountItems.load('heey'); 
    amountItems.speek(); 
}) 

var amountItems = (function() { 
    var el = "" 

    return { 
     load: function(str) { 
      el = str; 
     }, 
     speek: function() { 
      alert(el); 
     } 
    } 
}()) 
0

當你這樣做:

var amountItems = (function(el) { 
    // var el = el; 
    return { 
     speek: function() { 
      alert(el) 
     } 
    } 
}()) 

您執行一個包裝函數並將內部對象分配給amountItems
不要當您調用此參數時傳遞一個參數(el),因此el未定義。

amountItems是一個方法對象speek不是除了params。

的方式來做到這一點是:

var amountItems = { 
     speek: function(txt) { 
      alert(txt); 
     } 
    }; 

$("#foo").on("click", function() { 
    amountItems.speek('heey') 
})