简体   繁体   English

在回调中为对象的属性/变量分配值

[英]Assigning a value to a object's property/variable in a callback

var obj1={
    var1:"val1",
    init:function(){
        this.var1="val2";
        var self=this;
        setTimeout(function(){self.var1="val3"},1);
        setTimeout(function(){obj1.var1="val3"},1);
    }
}

obj1.init();
console.log(obj1.var1);
console.log(obj1);

How to set/assign a value to var1 in the setTimeout callback. 如何在setTimeout回调中将值设置/分配给var1。 Assigning val3 does not have an effect and as seen in the screenshot we have two properties mentioned as var1 now. 分配val3无效,如屏幕截图所示,我们现在有两个属性称为var1。 1 is var1=val2 and other is var1=val3 , but this.var1 always returns val2 not val3 1是var1 = val2,另一个是var1 = val3,但是this.var1总是返回val2而不是val3

在此处输入图片说明

Actually the value is set to "var3" in your code. 实际上,该值在您的代码中设置为“ var3”。 But in your demo, the console prints "var2" is because that console.log() fire earlier then that setTimeout(). 但是在您的演示中,控制台显示“ var2”是因为console.log() setTimeout()更早启动。 The variable changes after it print out. 变量在打印输出后更改。

check this jfFiddle for correct result. 检查此jfFiddle以获得正确的结果。

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

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