在此JavaScript代码中,为什么在比较时这两个函数直接返回True,而在使用新对象创建时比较时返回False?
function A() {
return this;
}
function B() {
return this;
}
console.log(A() === B());
console.log(new A() == new B());
答案 0 :(得分:3)
您应该注意,在JavaScript中,this
是指调用上下文或对函数进行调用的位置。
这样做的时候
function A() {
return this;
}
然后
console.log( A() );
出于明显的原因,调用上下文是window
上下文,因此,this
指的是window
。 B()
也是如此。
但是,当您执行new A()
时,将初始化该类的新实例以及一个新的内存位置。由于每个新的初始化都指向一个新的内存位置,因此它们永远不等于true
。
答案 1 :(得分:2)
在函数内的第一种情况下,this
引用window
对象。因此基本上是window === window
function A() {
return this; // this is the window object
}
function B() {
return this; // this is window object
}
在这种情况下,new A()
and new B()
指的是不同的内存位置,因此它们永远不相等