jquery 插件缺少元素上下文

jquery Plugin Missing Element Context

我正在使用官方 plugin guide 创建一个 jquery 插件。我的基本代码如下所示:

(function ($) {
    $.fn.categories = function(options) {

        var settings = $.extend({
            ...
        }, options);

        var init = function()
        {
            // `this` is undefined here 
        };

        // `this` points to $("#pick-category") here
        init();
        return this;
    };
}( jQuery ));

// usage
$(document).ready(function(){
    $("#pick-category").categories();
});

我的问题是,在函数 $.fn.categories 的上下文中,this 被定义并且确实引用了 $(#pick-category) jquery 对象。但是在从 $.fn.categories 函数调用的 init 函数的上下文中,this 报告为 undefined.

我的问题是,这是怎么回事?上下文是如何丢失的?

init 被定义为一个局部变量,它恰好是一个函数。它没有上下文,除了你给它的。它与它在其中声明的父函数无关。

所以使用 call() 给它一个上下文:

(function ($) {
    $.fn.categories = function(options) {

        var settings = $.extend({
            ...
        }, options);

        // define a local function unrelated to $.fn.categories or any other context
        var init = function()
        {
            // `this` is now $("#pick-category")
        };

        // `this` points to $("#pick-category") here

        // call the function with an explicit context
        init.call(this);

        return this;
    };
}( jQuery ));