从内部对象javascript设置字段值

set value of field from internal object javascript

本文关键字:字段 设置 javascript 内部对象      更新时间:2023-09-26

我有一个名为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");               
        }
    });
}