我有一个名为light的类,它通过ajax加载其状态:
function Light(name, channel, type, state) {
this.name = name;
this.channel;
this.type=type;
this.state = state; //0=off 1=on
this.turnOn = function () {
this.state = 1;
$('#luce-' + name).attr('src', controlImagePath + '' + type + '100.png');
}
this.turnOff = function () {
this.state = 0;
$('#luce-' + name).attr('src', controlImagePath + '' + type + '00.png');
}
this.toggle = function () {
if (this.state == 0) this.turnOn();
else this.turnOff();
}
this.checkState = function () {
var result;
$.jsonp({
callback: "callback",
url: 'http://' + serverAddress + ':' + serverPort + '/GetChannelValueAsJsonp?channelName=' + channel + '&callback=?',
success: function (data) {
if (data > 0) {
this.turnOn();
} else {
this.turnOff();
}
},
error: function (xOptions, textStatus) {
console.log("error");
}
});
}
}
它一直给出错误:
Uncaught TypeError: Object #<Object> has no method 'turnOn'
我怀疑是因为覆盖Light范围的成功功能。如何从另一个函数范围引用对象?
在Java中的IE我会做Light.this.turnOn()...如何做到这一点是javascript?
谢谢!
答案 0 :(得分:4)
this
是指jQuery / XHR对象。您必须将this
关键字保存在变量中:
this.checkState = function () {
var result;
var $this = this; //Saving `this`
$.jsonp({
callback: "callback",
url: 'http://' + serverAddress + ':' + serverPort + '/GetChannelValueAsJsonp?channelName=' + channel + '&callback=?',
success: function (data) {
if (data > 0) {
$this.turnOn(); //Referring to `this` through $this`
} else {
$this.turnOff();
}
},
error: function (xOptions, textStatus) {
console.log("error");
}
});
}