如何设置javascript闭包的上下文

How to set context of javascript closure?

本文关键字:javascript 闭包 上下文 设置 何设置      更新时间:2023-09-29

所以我有ValidationHelper.js,它包含一个闭包:

console.log(this) //context of the file is FormManager object
(function($) {
    console.log(this) //context of the closure is window
    ...
}(jQuery)

如何将闭包的上下文设置为FormManager对象?

您可以使用调用来设置上下文:

(function($) {
    console.log(this) //context of the closure is the outside this
    ...
}).call(this, jQuery)

在第一行中,这不是闭包!

检查此项:

(function($) {
    console.log(this);
}).call(this, jQuery)