繁体   English   中英

设置内部对象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的IE浏览器执行Light.this.turnOn()...如何使用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");               
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM