[英]Coffeescript / Javascript - why object attribute is undefined?
I have this function that I'm using it in a Rails 3.1 project: 我有这个函数,我在Rails 3.1项目中使用它:
setPosition: (object) ->
console.log object
console.log object.width
object["position"] = [500, 50]
this
The console.log object
gives console.log object
给出
Object
height: 600
position: Array[2]
title: "Banner for Creative"
width: 160
__proto__: Object
but console.log object.width
is undefined. 但是
console.log object.width
是未定义的。 Why ? 为什么?
I answered a similar question just a couple of days ago: https://stackoverflow.com/a/8299394/66226 几天前我回答了类似的问题: https : //stackoverflow.com/a/8299394/66226
Basically, console.log
has some asynchronous behaviors (in some environments). 基本上,
console.log
具有某些异步行为(在某些环境中)。 So when you pass in a reference to an object, that object is stringified later—whereas object.width
is undefined
right now. 因此,当您传入对象的引用时,该对象将在以后进行字符串化,而
object.width
现在是undefined
。
If you do 如果你这样做
console.log object.toString()
then you should get more consistent results (though less pretty ones). 那么您应该获得更一致的结果(尽管效果不佳)。
Edit: Or better yet, 编辑:或者更好,
console.log JSON.stringify(object)
See comments below. 见下面的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.