[英]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:
p2 : p2:
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.