[英]Calling Nested Function In Javascript - Is Not Defined Error When Called Within jQuery.ajax.success
我正在對象內部進行Ajax表單提交。
當我嘗試在jQuery.ajax.success回調中調用其他對象方法時,此行將引發錯誤...
這是范圍問題嗎?
this.DisplayError(data.error);
this.DisplayError不是函數
碼:
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: function(data) {
if(data.success === false) {
this.DisplayError(data.error);
}
console.log(data); // show response from the php script.
}
});
}
}
使用箭頭功能:
success: () => {
}
發生這種情況是因為您失去了上下文,調用成功函數時Ajax分配了不同的上下文。 您還可以將上下文保存在New變量中:
var self = this;
並在成功函數內使用它來代替它。 或者,您可以定義函數上下文:
success: (function() {
}).bind(this)
this
成功函數內部不等於this
之外。 解決此問題的最簡單方法是使用箭頭功能。
var toolsform = new function() {
this.sumbitUrl = 'submit.php';
this.DisplayError = function(errorMsg) {
jQuery('#trialFormError').html('<strong>Error: </strong>' + errorMsg);
}
this.AjaxSumbit = function() {
let formData = jQuery("#trialsToolsRegisterForm").serialize();
formData += '&toolsFormSumbit=1';
jQuery.ajax({
type: "POST",
url: this.sumbitUrl,
dataType: 'json',
data: formData,
success: data => {
if(data.success === false) {
this.DisplayError(data.error); // now `this` should be equal to the one outside
}
console.log(data); // show response from the php script.
}
});
}
}
魔術是,箭頭功能沒有它自己的this
。 當你調用this
,它會參考一個以外。 但是普通函數有它自己的this
,因此,當您調用this
,它將引用自己的this
而不是外部的this
。
有關詳細信息,您可以查看MDN網絡文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.