问题描述
var obj, method;
obj = {
go: function() { console.log(this); }
};
(method = obj.go)()
注意:Fyodor 对他的回答的第一条评论对我帮助最大.正如主题所暗示的那样,这更多是关于括号而不是 this
.
NOTE: Fyodor's first comment to his answer is what helped me the most. As the topic suggests, this was more about the parentheses than this
.
最后一行,我的理解是括号会强制里面的代码先运行,所以method
取的是go
属性的值,也就是一个函数.
In the last line, what I understand is that the parentheses will force the code inside to run first, so method
takes the value of the go
property, which is a function.
()
然后调用该函数,该函数将 window
记录到控制台,因为它不是作为方法调用的.
The ()
then calls that function, which logs window
to the console because it wasn't called as a method.
如果你使用 method = obj.go()
而不是 (method = obj.go)()
,它会首先运行 go
函数,method
会取其返回的值.由于 go
什么都没有返回,它将是 undefined
.go
打印的值将是 obj
.
If instead of (method = obj.go)()
, you do method = obj.go()
, it will first run the go
function, and method
will take the value returned by it. Since go
returns nothing, it will be undefined
. The value printed by go
will be obj
.
我不明白的是,为什么如果我执行 (obj.go)()
打印的 this
是 obj
而不是窗口
?
What I don't understand is, why if I do (obj.go)()
the this
printed is obj
and not window
?
考虑到其他代码的工作方式,我预计这段代码的工作方式如下:obj.go
首先在括号内求值,然后函数作为 IIFE (function() { console.log(this); })()
运行.所以由于函数不是作为obj
的方法调用的,this
默认为window
.
Considering how the other code works, I expected this code to work kind of like this:obj.go
is evaluated first inside the parentheses and then the function is run as an IIFE (function() { console.log(this); })()
. So since the function isn't called as a method of obj
, the this
defaults to window
.
推荐答案
(method = obj.go)()
分两步求值.
method = obj.go
被求值并且method
var 变成等于对象obj
的函数go
代码>.JavaScript 中的函数可以作为方法或函数调用,因此通常它不影响您如何定义函数go
.
method = obj.go
is evaluated andmethod
var become equal to functiongo
of objectobj
. Functions in JavaScript can be called as methods or as functions, so in general it doen't metter how you;ve defined functiongo
.
然后 method()
被调用.由于您没有为 this
提供值(通过调用 method
函数作为某个对象的方法或使用 bind
或 call
调用它时 this
设置为全局对象(在非严格模式下)或 undefined
(在严格模式下)
Then method()
is called. As you didn't provided value for this
(either by calling method
function as method of some object or using bind
or call
it is called with this
set to global object (in non strict mode) or to undefined
(in strict mode)
当你调用 obj.go()
this
被设置为等于 obj
(它类似于使用 obj.go.call(obj)
或 method.call(obj)
).如果你只调用 method()
this
等于全局对象(类似于调用 obj.go.call(window)
)
When you call obj.go()
this
is set equal to obj
(it is similar to use obj.go.call(obj)
or method.call(obj)
). If you call just method()
this
is equal to global object (similar to call obj.go.call(window)
)
编辑
并通过您的示例将 obj
作为 this
获取,您可以这样做
And to get obj
as this
with your example you can do such way
(method = obj.go.bind(obj))()
通过这种方式,您不仅可以将 go
函数分配给变量 method
,还可以创建到特定 this
的绑定等于 obj代码>
In this way you not only assign go
function to variable method
but create binding to specific this
equal to obj
这篇关于括号如何影响 JavaScript 中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!