1

I have this function that I'm using it in a Rails 3.1 project:

setPosition: (object) ->
    console.log object
    console.log object.width
    object["position"] = [500, 50] 
    this

The console.log object gives

Object
    height: 600
    position: Array[2]
    title: "Banner for Creative"
    width: 160
    __proto__: Object

but console.log object.width is undefined. Why ?

6
  • 3
    Please don't name your variables object, use a more descriptive name that avoids ambiguity with native objects. Commented Dec 1, 2011 at 2:39
  • Is this in chrome by any chance? Commented Dec 1, 2011 at 2:45
  • jm: your are right. I already changed it. Commented Dec 1, 2011 at 12:06
  • same behavior in Firefox Commented Dec 1, 2011 at 12:46
  • Could you add results for console.log (x for x of object) and console.log 'width' of object? It may be that there's a subtle string issue, such as the key name having a null character at the end. See my answer on another question today: stackoverflow.com/a/8344503/66226 Commented Dec 1, 2011 at 16:41

1 Answer 1

3

I answered a similar question just a couple of days ago: https://stackoverflow.com/a/8299394/66226

Basically, console.log has some asynchronous behaviors (in some environments). So when you pass in a reference to an object, that object is stringified later—whereas object.width is undefined right now.

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.

Sign up to request clarification or add additional context in comments.

10 Comments

+1 - I assumed he was getting an error. I never imagined console.log would have issues like this
Adam, I'm not getting an error, just 'undefined'. But if I try to access width or height directly ( object.height for instance ) same behavior.
console.log object.toString() gives [object Object]
@Aldo Ah, sorry; try JSON.stringify(object) instead of object.toString().
@Aldo Ah, I misread your post about what JSON.stringify shows—it is an async problem! My answer, as posted above, is correct. Everything but console.log object is showing the true state of the object at the time of the console.log; console.log object is storing a reference to the object, then displaying it later, after the object's fields have been populated. Use JSON.stringify when you want to avoid confusion! Make sense?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.