Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery插件缺少元素上下文_Jquery_Jquery Plugins - Fatal编程技术网

jquery插件缺少元素上下文

jquery插件缺少元素上下文,jquery,jquery-plugins,Jquery,Jquery Plugins,我正在使用官方软件创建一个jquery插件。我的基本代码如下所示: (function ($) { $.fn.categories = function(options) { var settings = $.extend({ ... }, options); var init = function() { // `this` is undefined here

我正在使用官方软件创建一个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
的上下文中,定义了
这个
,实际上是指
$(#pick category)
jquery对象。但是在从
$.fn.categories
函数调用的
init
函数的上下文中,
报告为
未定义


我的问题是,这里发生了什么?上下文是如何丢失的

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 ));