Javascript 类 + 属性不遵守它们的值

标签 javascript oop properties

我正在尝试用 javascript 创建一个类。我使用 JSON 类型对象创建它。

这样做:

Foo = {
   PubId: '',

   Init:function( oCallback )
   {
         this.sendCommand( 'INIT', {}, oCallback );
   },

    sendCommand : function( sCommand, aParams, oCallback )
    {

        setTimeout( oCallback, 1000, '{"response":"INIT","time":1287982024,"pubid":"4cc50bc47c7b3"}' );

        return true;
    },
    onData : function( sData )
    {
        var aRes = JSON.parse( sData );

        this.PubId = aRes.pubid;
        alert( this.PubId );
        return this.PubId;
    },
    umtest:function(){ alert( this.PubId ); }
}

然后我也在包含脚本后执行此操作:

Foo.Init( Foo.onData ); 

问题是 this.PubId 在 onData 方法内部更新,但在它之外,pubid 是空的。

我是 javascript 类(class)的新手,所以我不确定需要做什么,所以我希望有人能帮助我。 :)

感谢您的宝贵时间!

最佳答案

嗯,这里有两个问题。 第一个 问题是不理解 this 在 Javascript 中的工作原理。当通过 setTimeout( oCallback, ...) 调用 Foo.onData 时,this 将引用全局对象而不是 Foo.

为了用 Foo 调用它作为 this 你应该改变你的代码:

sendCommand: function (sCommand, aParams, oCallback) {
    var that = this;           // save this reference
    setTimeout(function () {
        oCallback.call( that,  // call the function with it
               '{"response":"INIT","time":1287982024,"pubid":"4cc50bc47c7b3"}' );
    }, 1000);
    return true;
},

为了测试发生了什么变化,将这段代码放在 onData 中:

// is `this` really Foo or the global object?
alert(this === Foo);    // should be true
alert(this === window); // should be false

在更新版本中,this 将正确引用 Foo 作为调用对象。

您可能面临的第二个问题是您使用setTimeout 调用的函数只会在1000 ms = 1s 后执行,因此如果您只是检查 Foo 之外的 alert(Foo.PubId),您将得到一个空字符串(因为尚未调用回调)。

为了测试 Foo.PubId 是否确实改变了:

// execute the check after 2s so as to
// make sure the callback has been called
setTimeout( function () {
  alert(Foo.PubId);
}, 2000);

您可以查看完整的测试用例here .

关于Javascript 类 + 属性不遵守它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4015092/

相关文章:

JAVA动态属性条件求值

url - 回调中的 ShareThis 设置属性不起作用

java - 写入由 ClassLoader 加载的 Wildfly 上的属性文件

javascript - 如何在javascript中移动元素

javascript - Rails 4 - 使用 AJAX/JS 渲染部分

oop - 我应该保留设计模式术语吗?

ios - 你什么时候会在包中而不是属性中声明变量?

javascript - 使用不带 FormData 的 AJAX 上传文件 (IE9)

javascript - 如何设置事件监听器以使用 JavaScript 监听 HTML 源代码中的文本框?

c++ - 类的实例只允许 1 个方法,否则程序崩溃