gpt4 book ai didi

javascript - 对象与普通函数

转载 作者:行者123 更新时间:2023-12-03 04:58:53 24 4
gpt4 key购买 nike

//代码开始

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”

最佳答案

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

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

编辑。添加了代码示例

关于javascript - 对象与普通函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com