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?

8
  • Output is - Response - how can the output be "Response" ... surely it's a "Person" object Commented Jan 27, 2017 at 8:19
  • @JaromandaX, it's a link to an image. Commented Jan 27, 2017 at 8:20
  • I know ... why couldn't the OP put that in the question Commented Jan 27, 2017 at 8:20
  • Response is a hyperlink showing that the object firstname has been console logged before it has been set in the code. Commented Jan 27, 2017 at 8:20
  • 2
    console.log can be misleading ... try console.log(JSON.stringify(this)) and console.log(JSON.stringify(sam)); to get a true snapshot Commented Jan 27, 2017 at 8:21

2 Answers 2

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation
1

Firefox logs

Object {  } 
Object { firstname: "Sam" }

So, your browsers console is lying to you

Comments

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.