如何从 jquery 中编辑属性变量,如下例所示:
function Timetable(){
this.timetables=[];
//get timetable data for currentUser
$.get('http://someurl.com/api',function(data){
this.timetables.concat($.parseJSON(data));
});
}
似乎发生的情况是 this.timetables 似乎超出了变量范围。
最佳答案
您不需要使用this
,您需要创建一个closure .
function timetable(){
// create a closure
var timetables = Array();
//get timetable data for currentUser
$.get('http://someurl.com/api',function(data){
// this references the Array created above
that.timetables = that.timetables.concat($.parseJSON(data));
});
}
我刚刚想到您可能正在使用timetable
来创建对象。附带说明一下,如果是这种情况,为了清楚起见,惯例将其称为 Timetable
。如果是这种情况,请使用类似的东西。
function Timetable () {
// store a reference to the scope
var that = this;
// create an instance property of the Timetable object
this.timetables = [];
$.get('http://someurl.com/api',function(data){
// use our scope reference captured above
// to update the timetables property
that.timetables = that.timetables.concat($.parseJSON(data));
});
}
var t = new Timetable();
// once the get call is complete
console.log(t.timetables);
关于Javascript OOP 和 jQuery 无法触及对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518849/