【问题标题】:Object vs normal function对象与正常功能
【发布时间】:2017-02-18 13:39:55
【问题描述】:

// 代码开始

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:人员 {name: "Object_Shashank"}

p2:

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

谁能解释一下“p2:输出2”

【问题讨论】:

标签: javascript


【解决方案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")

编辑。添加代码示例

【讨论】:

  • 谢谢。很有帮助
猜你喜欢
  • 2012-12-09
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多