无法在javascript对象上设置属性(Can't set property on javascript object)

编程入门 行业动态 更新时间:2024-10-24 08:30:01
无法在javascript对象上设置属性(Can't set property on javascript object)

全文: https : //gist.github.com/jonny2779/1e59c3a97b910b09240c

Self是一个js模型,里面有所有方法。

Moodboard.prototype = {

代码:

var self = this; self.isArchived = true; self.foo = true; console.log('is archived property', self.isArchived); console.log('self object', self); return self.save();

这段代码的结果:(注意self.foo已设置)

[ true 独立 isArchived 属性,但 false 属性在对象内[1]">

为什么在设置self.foo时没有设置self.isArchived?

另外,为什么在我执行object.property时设置,而不是在我只记录对象时?

TLDR;

Console.log()是异步的。 在我的屏幕截图中,它显示了设置为我想要的属性。 当您展开console.log(); 它似乎“重新启动”事件,并可以获得不同的价值观。 这是因为save()方法也是异步并且操纵原始对象。

Full gist: https://gist.github.com/jonny2779/1e59c3a97b910b09240c

Self is a js model with all the methods inside it.

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)

[true standalone isArchived property but false property inside object][1]">

Why is self.isArchived not being set when self.foo is being set?

Also, why is it set when i do object.property and not when I log just the object?

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是异步的:当您记录self对象时,只记录一个引用,当您单击它时会对其进行评估。

请注意以下截图 :在控制台消息的第一行(未打开状态)中, isArchived按预期为true 。 只有当您手动打开它以进一步检查时才会将其列为false 。 可能还有其他东西在记录和手动打开之间修改它。

(我敢打赌,如果你直接记录self.isArchived,你就不会看到这种行为,因为它是一个可以立即打印的原始值。)

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.

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.

(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.)

更多推荐

本文发布于:2023-08-01 04:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353843.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象   javascript   object   property

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!