首先,你的代碼表明,要呼叫show
的#something
單擊事件的內部。
其次,當你在初始化的背景下正在執行的,除非你說methods.init.call(...)
以代替...
一些其他的對象,然後this
會methods
。很可能,您將使用語句methods.init()
。如果您只是將對象methods
作爲插件傳遞給某個jQuery小部件,則這是正確的假設。以下將在這種情況下工作:
var methods = {
init: function(options) {
this.show();
},
show: function() {}
}
除非你想使用點擊事件。在這種情況下,使用方法:
var methods = {
init: function(options) {
$('#something').click(function() {
this.show();
}, this); // propogate this into click handler
},
show: function() {}
}
如果您希望您將運行methods.init.call(...)
,那麼你將需要確保建立一個封閉的範圍預先保持原有methods
對象的軌跡:
var methods = function() {
// setup closure scope
var that = {}; // keep track of methods object
that.init = function() {
that.show();
};
that.show = function() {
};
// return object with closure scope... will become `methods`
return that;
}();