我遇到了“这个”问题,希望得到任何帮助
这是我的基本代码
function xxx(val)
{
this.x = val;
this.change = function() {
var self = this;
$.ajax({
blah: '',
blah: '',
success: function(data) { self.x = 5; },
});
};
}
var newX = new x(1);
newX.change();
console.log(newX.x);
希望这是有道理的,
我想做的是更新 jquery ajax 响应中的原始对象。我无权访问“this”,所以我试图将它传递给“self”变量,但即使代码按预期运行,对象值似乎也没有更新。
我确信有一个简单的答案,我只是不知道。
非常感谢任何帮助。
最佳答案
因此,解决此问题的方法是查看您的函数声明。每个函数声明都会为您提供一个新的 this
对象。将您感兴趣的那个存放在正确的位置。如果我是对的,看起来您实际上想要访问原始 xxx 函数范围的范围。因此,与其将 this
存储在 change
函数中,不如将其存储在原始作用域的上方。像这样:
function xxx(val)
{
var self = this;
this.x = val;
this.change = function() {
var that = this;
$.ajax({
blah: '',
blah: '',
success: function(data) { self.x = 5; },
});
};
}
var newX = new x(1);
newX.change();
console.log(newX.x);
这里的另一个问题是您正在使用 AJAX 进行调用,因此您需要一个 Deferred 对象,或者您可以向该函数添加一个回调,以便在正确的时间触发,如下所示:
function xxx(val)
{
var self = this;
this.x = val;
this.change = function(callback) {
var that = this;
$.ajax({
blah: '',
blah: '',
success: function(data) {
self.x = 5;
if (typeof callback === "function"){
callback.call(this);
}
}
});
};
}
var newX = new xxx(1);
newX.change(function(){
console.log(newX.x);
});
关于javascript - KnockoutJS - 使用内部函数更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099393/