[英]js function comparison with objects
In this JavaScript code , why the two functions when compared directly returns True while when compared using new object creation returns False? 在此JavaScript代码中,为什么两个函数在比较时直接返回True,而在使用新对象创建时比较时返回False?
function A() { return this; } function B() { return this; } console.log(A() === B()); console.log(new A() == new B());
You should be aware that in JavaScript, this
refers to the calling context or the place where the call to the function was made. 您应该意识到,在JavaScript中,
this
是指调用上下文或调用函数的位置。
When you do 当你做
function A() {
return this;
}
then 然后
console.log( A() );
The calling context, for obvious reasons, is the window
context and hence, this
refers to window
. 出于明显的原因,调用上下文是
window
上下文,因此, this
是指window
。 Same is the case with B()
. B()
也是如此。
However, when you do new A()
, you initialize a new instance of the class and, vis-a-vis, a new memory location. 但是,当您执行
new A()
,您将初始化该类的新实例以及一个新的内存位置。 Since each new initialization refers to a new memory location, they never equate to true
. 由于每个新的初始化都指向一个新的内存位置,因此它们永远不等于
true
。
In first case this
inside the function refers to the window
object. 在第一种情况下,函数内部的
this
对象引用window
对象。 So it is basically window === window
which is true 所以基本上是
window === window
这是真的
function A() {
return this; // this is the window object
}
function B() {
return this; // this is window object
}
In this case new A()
and new B()
refers to the different memory location, so they are never equal 在这种情况下,
new A()
and new B()
指向不同的内存位置,因此它们永远不会相等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.