我有这个函数func
,它总是作为func.bind(this)
调用。对于 func
,隐式假设函数的 this
上下文始终是调用者的 this
上下文。这看起来有点重复,像这样调用 func
显然会导致误用,因为一些用户很容易忘记调用 func
而不将其绑定(bind)到 this
。我想知道是否有一种简洁的方法来始终使用其调用者的 this
上下文。
我正在考虑使用一种高阶方法来强制用户输入调用者的上下文。该方法如下所示:
function createFunc(context) {
return function func() {
// rather than call `this`, you use the input parameter, `context`.
}
}
最佳答案
I was wondering if there is a concise way to always use the
this
context of its caller.
您基本上似乎在要求动态范围。 this
获取其值的方式是动态的,但大多数情况下都是显式的。您似乎想要一个隐式获取其调用范围的 this
值的函数。
这在 JavaScript 中是不可能的。调用者必须通过 f.call(this)
或 f.apply(this)
显式设置 this
值。
关于javascript - 是否有一个 Javascript 习惯用法,其中函数 `func` 被称为 `func.bind(this)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840199/