问题描述:

// 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"

网友答案:

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

相关阅读:
Top