【发布时间】:2018-08-20 12:48:01
【问题描述】:
我有一个 x 类 C 的对象。属性x.myval 应通过调用x.load() 来设置,而x.load() 又应从异步ajax 调用中获取其数据。
class C {
constructor() {
this.myval = "hello";
}
load() {
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: function(text) {
this.myval = text;
}
});
}
}
var x = new C();
$.when(x.load()).done(function(a1,a2) {
console.log(x.text); //should print the content of file.txt
});
我收到错误this.myval is undefined,显然是因为this 设置为jquery-$ 的this。
我也试过了:
class C {
constructor() {
this.myval = "hello";
}
load() {
var callback = function callbackClosure(mythis) {return function(text) {
this.myval = text;
}}(this);
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: callback
});
}
}
var x = new C();
$.when(x.load()).done(function(a1,a2) {
console.log(x.text); //should print the content of file.txt
});
但这导致了一个例外jQuery.Deferred exception: assignment to undeclared variable...
【问题讨论】:
-
使用箭头函数。
标签: jquery asynchronous-javascript