3

I'm trying to understand how js prototypes and classes work, and I'm using Chrome's console.log to print and have a look at the state of my objects while I add new properties etc.

This is the code I'm using: (fiddle)

function Person(){}

Person.prototype.sayHello = function(){ alert("Hello"); };
Person.prototype.name = "Name";

console.log(Person.prototype) //1st console.log

Person.prototype.surname = "Surname";

console.log(Person.prototype); //2nd console.log

I expect to have two different results printed in the console, because the surname property was added after the first console log. Instead, this is the console output:

enter image description here

As you can see, both the outputs have the surname property defined even if it was added only after the 1st console.log..

Can you explain me why? What am I missing? Doesn't console.log show the current state of the object when called?

Thank you in advance, best regards

BeNdErR
  • 17,471
  • 21
  • 72
  • 103

1 Answers1

3

your next line of code where you set the persons surname, doesnt wait for the console log because console.log is asynchrounous, when you try out this code with a timeout it will be correct,

 function Person() {}

 Person.prototype.sayHello = function () {
     alert("Hello");
 };
 Person.prototype.name = "Name";

 console.log(Person.prototype) //1st console.log
 setTimeout(function(){
  Person.prototype.surname = "Surname";

 console.log(Person.prototype); //2nd console.log
 },1000);

you could save a copy of that object before you log it, then it would work

Synchronous console logging in Chrome

UPDATE: i have an even better solution :
just log a stringifyed version of the object and you´ll be okay

console.log(JSON.stringify(Person.prototype))
Community
  • 1
  • 1
john Smith
  • 17,409
  • 11
  • 76
  • 117
  • have a look at this [this](http://jsfiddle.net/b4VP3/1/) fiddle: if you wait both the console.log before you open the object hierarchy, hte `surname` is present in both.. if you open the 1st object while waiting for the 2nd log, the `surname` is not shown.. why :O? – BeNdErR Mar 03 '14 at 12:34
  • hmn for me "surname" is only present in the second log on latest chrome on mac osx – john Smith Mar 03 '14 at 13:00
  • also if you wait for the second log to appear and then (and only then) you open the Person object? – BeNdErR Mar 03 '14 at 13:22
  • as i said, you can just copy the object and log the copied instance, but yes, this is weird :D – john Smith Mar 03 '14 at 13:36
  • 3
    *"your next line of code where you set the persons surname, doesnt wait for the console log because console.log is asynchrounous"* No, `console.log` is not asynchronous. But the console keeps a live reference to the object, and *expanding* the object in the console is asynchronous. Sometimes. Depending on whether the console was open when you logged, amongst other things. – T.J. Crowder Sep 14 '15 at 17:02