0

Possible Duplicate:
Why does javascript object show different values in console in Chrome, Firefox, Safari?

I'm quite new to be using javascript's OOP concepts. I'm trying to understand the binding of javascript properties. Does javascript execute the below code, sequentially?

 // main.js
 function NameClass(){
   this.name = "John"
   this.age = 25
 }

 NameClass.prototype.change_my_name = function(new_name){
   this.name = new_name
 }

 NameClass.prototype.change_my_age = function(new_age){
   this.age = new_age
 }


 // main.html
  <html>
    <head>
      <title>Javascript tutorial</title>
        <script src="main.js"></script>
        <script>
          var nc = new NameClass()

          console.log("nc before modification")
          console.log(nc) // Prints Doe

          nc.change_my_name("Doe")

          console.log("nc after modification")
          console.log(nc) // Prints Doe
        </script>
      </head>
    <body></body>
  </html>

Now, what is trick here?

  1. Why do I see "Doe" display both the times?
  2. What is the mechanism that I've to use here in order to display "John" the first time and "Doe" in the second?
2
  • 1
    I assume you're using Chrome? This is a known bug with logging objects in the Chrome developer console. Commented Oct 26, 2012 at 17:42
  • Right. nc.name displays the values fine. Commented Oct 26, 2012 at 17:47

1 Answer 1

4

console.log() will not necessarily log the value the variable had at the time you tried to log it.

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

9 Comments

... without an interrupt. Do the same thing with an 'alert'. You'll see the value change.
... or test it with QUnit. You'll see the two different values.
Or just get the desired log value as a string (not an object) and log that. It works when using strings, just not when using objects.
@jfriend00 : Firefox logs the object state as expected. The problem is in Chrome when we try to log objects. Though, logging strings works fine in both the browsers
@Vineeth - yes I know it's a Chrome issue. I was suggesting that if you only pass a string to console.log(), then you don't have an issue in Chrome.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.