我正在尝试用 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/