[英]How a function passes its arguments to its inner function call (not nested new functions) in Javascript?
[英]How to call parent functions from inner nested function?
我有一個簡單的jQuery ready
事件,該事件通過在setupView
對象中調用a函數來初始化視圖。
我的問題是,從init
函數調用函數setSomethingImportant
合適方法如下所示?
由於調用是從與init
函數不同的執行上下文中進行的,因此this.setSomethingImportant()
不起作用。 但是,如果我使用setupView.setSomethingImportant()
它將起作用。 我的問題是,如果var名稱( setupView
)更改,我也將不得不更改代碼正文。
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant();
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);
保存this
到一個變量:
var setupView = {
currentState: "CT",
init: function() {
// Keep a reference to 'this'
var self = this;
$("#externalProtocol").change(function() {
console.log("Changed =" + $(this).val());
// Use the old 'this'
self.setSomethingImportant();
});
},
setSomethingImportant: function() {
this.currentState = "TC";
console.log("Something has changed :" + this.currentState);
}
};
請參閱工作演示 。
只需分別聲明函數,然后像這樣調用:
function setSomethingImportant(context) {
context.currentState="TC";
console.log("Something has changed :" + context.currentState );
};
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant(this);
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
setSomethingImportant(this);
}
}
}(jQuery);
請注意,我更改了原始解決方案。 我現在正在使用Even.data將數據傳遞給事件處理程序。
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change({ _this: this }, function (event) {
console.log("Changed =" + $(this).val());
event.data._this.setSomethingImportant();
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.