对象与普通函数

时间:2017-02-18 13:39:56

标签: javascript

//代码开始

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");

//代码结束

p1:

  • 输出1:Object_Shashank
  • 输出2:人{姓名:" Object_Shashank"}

p2:

  • 输出1:Function_Shashank
  • 输出2:窗口{speechSynthesis:SpeechSynthesis,caches:CacheStorage,localStorage:Storage,sessionStorage:Storage,webkitStorageInfo:DeprecatedStorageInfo ...}

有人可以解释" p2:输出2"

1 个答案:

答案 0 :(得分:1)

它打印window对象,因为this引用了窗口对象。

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

编辑。添加了代码示例