函数内部的“this”与函数无关

`this` inside function has nothing to do with a function?

本文关键字:函数 this 内部      更新时间:2024-01-07
var f2 = undefined
var f1 = function () {
    f2 = this
    console.log('here')
}
f1()
f2()

输出

f2()
^
TypeError: undefined is not a function

如何从 f2(( 内部将 f1 设置为 f1?

这实际上不是设置它的正确方法,但即使是这样,您也从未调用过f1,因此f2的值永远不会改变。您将需要这个:

var f2 = undefined;
var f1 = function () {
    f2 = this;
    console.log('here');
}
f1();
f2();

也就是说,上述方法仍然不起作用,因为独立函数内部this不是函数。在浏览器中,它将是window对象,你会得到类似 TypeError: object is not a function .在其他上下文(例如,node.js(中,这将取决于它们如何实现顶级对象(如果有的话(。

有一个很好的问题解释了函数如何使用this关键字。在这种情况下,如果不按名称引用外部函数或更改调用f1的方式,您将无法执行此操作:

// Referring to f1 by name..
var f2 = undefined;
var f1 = function () {
    f2 = f1;
    console.log('here');
}
f1();
f2();
// .. or using the apply method to change the value of "this", though still
// referring to f1 by name in some sense (at the call site)
var f2 = undefined;
var f1 = function () {
    f2 = this;
    console.log('here');
}
f1.apply(f1);
f2();

旁注,分号省略号很恶心。

我不确定没有包装器有什么方法可以做到这一点。

var wrapper = {}
wrapper.f1 = function () {
    wrapper.f2 = wrapper.f1
    console.log('invoked', this)
}
wrapper.f1()
wrapper.f2()

我不确定这是否适用于您的实际用例。

var whatIsThis = function() {
    console.log('invoked', this)
}
whatIsThis()

在相关说明中,第二个示例显示了浏览器中的窗口对象。我不确定它会在节点中显示什么。