为什么这会返回3,1? [英] Why does this return 3, 1?
问题描述
我理解后者,我们在 foo
对象上调用警报,该对象有另一个名为 baz
的对象as它的属性,它又有一个名为 bar
的方法,它返回 x
的值。并且由于词汇范围
(我认为:))JS编译器/解释器上行,找到 x
in baz
并返回1.
I understand the later, we call the alert on the foo
object, which has another object named baz
as its property, which in turn has a method named bar
that returns the value of x
. And because of lexical scope
(I think :) ) the JS compiler/interpreter goes up the chain, finds x
in baz
and returns 1.
我的猜测是分配给变量 go
然后从全局范围调用,你得到3?只是想知道背景中发生了什么。任何帮助将不胜感激!!!
My guess is when assigned to the variable go
and then called from the global scope, you get 3? Just want to find out what's happening in the background. Any help will be appreciated!!!
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());
推荐答案
当你这样做时:
var go = foo.baz.bar;
go();
你会发现 go
已经失去了在调用 bar()
之前引用 foo.baz
。它只是一个指向 bar
函数的指针,并且与它所附加的对象没有任何关联。这意味着当栏$ c $时,
此
将不会是 foo.baz
c>方法执行。
you will find that go
has lost the reference to foo.baz
before calling bar()
. It is just a pointer to the bar
function and has no association with the object that it is attached to any more. That means that this
will not be foo.baz
when the bar
method executes.
这显然是为 .bind()
开发的。您可以这样使用它:
This is explicitly what .bind()
was developed for. You can use it like this:
var go = foo.baz.bar.bind(foo.baz);
go();
然后,它将适合您。你也可以做同样的手动版本:
And, it will then work for you. You can also do the manual version of the same thing:
var go = function() {return foo.baz.bar();}
go();
但内置了 .bind()
现在该语言可以帮助您解决此类问题。
but .bind()
is built into the language now to help you solve this type of issue.
这篇关于为什么这会返回3,1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!