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"

m87
  • 4,445
  • 3
  • 16
  • 31
Shashank Shekhar
  • 351
  • 3
  • 11
  • `Person()` = `window.Person()` –  Feb 18 '17 at 13:44
  • you've forgotten `new` keyword before `Person` – RomanPerekhrest Feb 18 '17 at 13:45
  • 2
    Possible Duplicate of [What is the difference between "new Number(...)" and "Number(...)" in JavaScript?](//stackoverflow.com/q/2381399) – Tushar Feb 18 '17 at 13:45
  • 3
    Possible duplicate of [What is the difference between "new Number(...)" and "Number(...)" in JavaScript?](http://stackoverflow.com/questions/2381399/what-is-the-difference-between-new-number-and-number-in-javascript) – Rahul Feb 18 '17 at 13:49

1 Answers1

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

Sachin Gadagi
  • 749
  • 5
  • 14