jquery插件缺少元素上下文
我正在使用官方软件创建一个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
(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 ));