在Titanium下开发我用OOP JavaScript和事件处理程序范围来掩盖这种奇怪的行为.这是我的代码:
MyClass = function()
{
this.var1 = '50';
this.button = Ti.UI.createButton({
...
});
this.button.parentRef = this;
this.button.addEventListener('click', function(e){
var self = e.source.parentRef;
console.log(self.var1);
console.log(self.var2);
});
this.var2 = 'Test';
...
/* this.button is then added to a view */
};
...
var c = new MyClass();
...
Run Code Online (Sandbox Code Playgroud)
当我点击按钮时,在我的控制台中我希望找到:
50
Test
Run Code Online (Sandbox Code Playgroud)
但实际上结果是:
50
<null>
Run Code Online (Sandbox Code Playgroud)
如果我移动作业
this.var2 ='测试'
之前
this.button.addEventListener
声明,结果是:
50
Test
Run Code Online (Sandbox Code Playgroud)
听起来像this.button.parentRef =这个赋值是复制而不是引用...
这种行为的原因是什么?