Full gist: https://gist.github.com/jonny2779/1e59c3a97b910b09240c
全文:https://gist.github.com/jonny2779/1e59c3a97b910b09240c
Self is a js model with all the methods inside it.
Self是一个js模型,里面有所有方法。
Moodboard.prototype = {
The code:
var self = this;
self.isArchived = true;
self.foo = true;
console.log('is archived property', self.isArchived);
console.log('self object', self);
return self.save();
The results of this code: (Note that self.foo is set)
这段代码的结果:(注意self.foo已设置)
[
Why is self.isArchived not being set when self.foo is being set?
为什么self.isArchived在设置self.foo时没有被设置?
Also, why is it set when i do object.property and not when I log just the object?
另外,为什么在我执行object.property时设置,而不是在我只记录对象时?
TLDR;
Console.log() is async. In my screenshot it shows the property set to what I wanted. When you expand a console.log(); it seems to 're-fire' the event and can get different values. This is because the save() method is also async and manipulates the original object.
Console.log()是异步的。在我的屏幕截图中,它显示了设置为我想要的属性。当您展开console.log();它似乎“重新启动”事件,可以获得不同的价值观。这是因为save()方法也是异步并且操纵原始对象。
1 个解决方案
#1
The issue arises from console.log being asynchronous: when you log the self object, only a reference is logged, which gets evaluated when you click on it.
问题源于console.log是异步的:当您记录self对象时,只记录一个引用,当您单击它时会对其进行评估。
Notice this in your screenshot: in the first line of the console message (unopened state), isArchived
is true
as expected. Only when you open it manually to inspect further is it listed as false
. Probably something else is modifying it between logging and manual opening.
请注意以下截图:在控制台消息的第一行(未打开状态)中,isArchived按预期为真。只有当您手动打开它以进一步检查时,它才会被列为false。可能还有其他东西在记录和手动打开之间修改它。
(I bet you would not be seeing this behaviour if you logged self.isArchived directly, because as a primitive value that would be printed immediately.)
(我敢打赌,如果你直接记录self.isArchived,你就不会看到这种行为,因为它是一个可以立即打印的原始值。)
#1
The issue arises from console.log being asynchronous: when you log the self object, only a reference is logged, which gets evaluated when you click on it.
问题源于console.log是异步的:当您记录self对象时,只记录一个引用,当您单击它时会对其进行评估。
Notice this in your screenshot: in the first line of the console message (unopened state), isArchived
is true
as expected. Only when you open it manually to inspect further is it listed as false
. Probably something else is modifying it between logging and manual opening.
请注意以下截图:在控制台消息的第一行(未打开状态)中,isArchived按预期为真。只有当您手动打开它以进一步检查时,它才会被列为false。可能还有其他东西在记录和手动打开之间修改它。
(I bet you would not be seeing this behaviour if you logged self.isArchived directly, because as a primitive value that would be printed immediately.)
(我敢打赌,如果你直接记录self.isArchived,你就不会看到这种行为,因为它是一个可以立即打印的原始值。)