简体   繁体   English

对象与正常功能

[英]Object vs normal function

// 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 : p1:

  • Output 1: Object_Shashank 输出1:Object_Shashank
  • Output 2: Person {name: "Object_Shashank"} 输出2:人{name:“ Object_Shashank”}

p2 : p2:

  • Output 1: Function_Shashank 输出1:Function_Shashank
  • Output 2: Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…} 输出2:窗口{语音合成:语音合成,缓存:CacheStorage,本地存储:Storage,会话存储:Storage,WebkitStorageInfo:DeprecatedStorageInfo…}

Can someone please explain "p2: Output 2" 有人可以解释“ p2:输出2”

It prints the window object because the this references the window object. 它打印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")

Edit . 编辑 Added the code example 添加了代码示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM