2

I have the following code

function Person(name){
  console.log(this);
  this.firstname=name;
}

var sam=new Person("Sam");
console.log(sam);

Output is - Response

When a new Object is created, initially this should point to an empty object. Why it has the updated response?

Sam
  • 189
  • 2
  • 10
  • `Output is - Response` - how can the output be "Response" ... surely it's a "Person" object – Jaromanda X Jan 27 '17 at 08:19
  • @JaromandaX, it's a link to an image. – Ionut Necula Jan 27 '17 at 08:20
  • I know ... why couldn't the OP put that in the question – Jaromanda X Jan 27 '17 at 08:20
  • `Response` is a hyperlink showing that the object firstname has been console logged before it has been set in the code. – NibblyPig Jan 27 '17 at 08:20
  • 2
    console.log can be misleading ... try `console.log(JSON.stringify(this))` and `console.log(JSON.stringify(sam));` to get a true snapshot – Jaromanda X Jan 27 '17 at 08:21
  • Possible duplicate: [Google Chrome console.log() inconsistency with objects and arrays](http://stackoverflow.com/questions/24175017/google-chrome-console-log-inconsistency-with-objects-and-arrays), and [Webkit bug 35801](https://bugs.webkit.org/show_bug.cgi?id=35801). – Amadan Jan 27 '17 at 08:29
  • Possible duplicate of [console.log() shows the changed value of a variable before the value actually changes](http://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch) – gzc Jan 27 '17 at 08:32
  • by the time chrome process it in dev tools constructor is already finished. – webduvet Jan 27 '17 at 08:34

2 Answers2

2

When you press the 'dropdown' icon in chrome console to inspect the object, it will -then- start evaluating the object itself at that memory location. So at the moment you press it, the property firstname is already filled.

If you try:

console.log(this.firstname);

You will see:

undefined

Sam

You can also try it using:

console.log(JSON.stringify(this))

This will disable the ability to navigate through the object though. If it's just a plain object you can do this:

console.log(JSON.parse(JSON.stringify(this)))
Community
  • 1
  • 1
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
1

Firefox logs

Object {  } 
Object { firstname: "Sam" }

So, your browsers console is lying to you

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87