0

// Code Starts

function Person(name) {
    this.name = name;
    console.log(this.name); //Output 1    
    console.log(this); //Output 2    
}
var p1 = new Person("Object_Shashank");
var p2 = Person("Function_Shashank");

// Code Ends

p1 :

  • Output 1: Object_Shashank
  • Output 2: Person {name: "Object_Shashank"}

p2 :

  • Output 1: Function_Shashank
  • Output 2: Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}

Can someone please explain "p2: Output 2"

4

1 Answer 1

1

It prints the window object because the this references the window object.

function Person(name){   
    this.name=name;    
    console.log(this.name); //Output 1    
    console.log(this);  //Output 2    <-- this `this` will point to the object it belongs to ,  which in this case of p1  is Object_Shashank while for p2 is window
}    
var p1=new Person("Object_Shashank");   
var p2=Person("Function_Shashank");  // Equivalent to p2 = window.Person("Function_Shashank")

Edit . Added the code example

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

1 Comment

Thank You. It is helpful

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.