我知道顶级函数是 window
的成员对象,与 this
一致它们里面指的是 window
.
但是对于非顶级函数,this
仍然是window
,但他们不是 window
的成员!
这是一些代码:
function topLevel1() {
alert(this)
}
function topLevel2() {
function inner() {
alert(this)
}
inner()
}
topLevel1() // alerts DOMWindow
alert(window.topLevel1) // alerts text of topLevel1, as expected
topLevel2() // again, alerts DOMWindow
alert(window.inner) // undefined
alert(window.topLevel2.inner) // undefined
- 如果
inner
既不是window
的成员也不属于topLevel2
,是谁的成员? - 怎么会是
this
是window
,但它不是window
的成员(member)? - 这不是 Javascript 中的一条定律:如果
this == owner
,然后通过owner.
调用当前方法? (特殊情况除外,如构造函数、apply
、call
等)
最佳答案
同样,this
函数的值(value)取决于函数的调用方式,而不是函数的位置或设计方式。
如果你只是调用一个函数
foobar()
代码中的任何位置,就像这样,它的 this
值将始终是 window
(非严格模式)或undefined
(严格的)。现在有很多方法可以修改this
,就像用 .apply()
调用函数一样, .call()
或.bind()
。所有这些方法都让您有机会修改 this
给定函数的值。另外,如果您使用 new
调用函数关键字,this
引用一个新创建的对象(也返回)。
因此,函数的位置告诉您其上下文为零或 this
.
现在回答您的具体问题:
inner
是Activation Object
的成员来自topLevel2
(ES3)如上所述
我想上面也涵盖了
关于javascript - 非顶级函数是任何对象的成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9814733/