2016-01-20 71 views
0

我正在创建一个jQuery插件使用官方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对象。但是在init函数(从$.fn.categories函数调用该函数,this报告为undefined)的上下文中。

我的问题是,这里发生了什么?情境如何丢失?

回答

0

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