从内部对象javascript设置字段值
set value of field from internal object javascript
我有一个名为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中,我将使用light .this.turn()…如何做到这一点是javascript?
谢谢!
XHR回调函数中的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");
}
});
}
相关文章:
- 如何将Date字段设置为等于另一个Date+Int值,该值表示月份值
- Sencha触摸,字段设置为Change Listener
- 将字段设置为有条件地使用所需的字段验证器
- crm 2011 javascript将日期字段设置为null
- 如何在自定义指令中将字段设置为$dirty
- javascript函数将上传文件字段设置为deafult
- 根据角度中的另一个字段设置输入字段的默认值
- Yii2 输入字段设置禁用取决于其他字段
- JavaScript for HTML5 必填字段设置为在 Safari 中工作
- 在 podio 中将计算日期字段设置为 null(因此使用 javascript)
- MongoDB:确保只有一个文档可以将字段设置为 true
- HTML 输入字段设置范围
- 如何使用 eval() 为作为参数提供的字段设置值
- j查询如何将值从输入字段设置为其他元素数据属性
- 使用具有金钱掩码的字段设置动态最大值
- 将输入字段设置为包含 window.location.href
- 根据下拉选择将输入字段设置为必填字段
- 从输入字段设置变量
- 从html输入字段设置javascript变量
- 如何在angularjs 1.3中将表单中的特定字段设置为dirty