2013-10-11 33 views
0

我不知道如何在fadeOut完成后访问匿名函数中该特定实例的插件“选项”。访问对象实例变量在匿名函数中的作用域

在匿名函数 '这个' 代表了jQuery的元素,我该如何访问 '?options.name“

这是插件 'plugin.js':

(function ($, window, document, undefined) { 

    'use strict'; 

    var plugin = 'box', 
     defaults = { 
      wight: 26, 
      color: 'white' 
     }; 

    function Plugin(element, options) { 
     this.plugin = plugin; 

     this.element = element; 

     this.options = $.extend({}, defaults, options); 

     $(this.element).fadeOut(1000, function() { 
      console.log(this.options.name);   // <- how do I access options.name? 
     }); 
    } 

    Plugin.prototype = { 
     f: function() { 
      console.log(this.options.name); 
     } 
    }; 

    $.fn[plugin] = function (argument) { 
     var method = argument, 
      options = argument; 

     return this.each(function() { 
      if (!$.data(this, 'plugin_' + plugin)) { 
       $.data(this, 'plugin_' + plugin, new Plugin(this, options)); 
      } else if ($.isFunction(Plugin.prototype[method])) { 
       $.data(this, 'plugin_' + plugin)[method](Array.prototype.slice.call(arguments, 1)); 
      } else { 
       console.error('unknown method ' + method); 
      } 
     }); 
    }; 
}(jQuery, window, document)); 

这是'的index.html':

<!DOCTYPE html> 
<html class="no-overflow"> 
    <head> 
     <meta charset="UTF-8"> 

     <title>Table example</title> 

     <!-- jqwidgets styles --> 
     <style type="text/css"> 

     </style> 

     <!-- jquery framework --> 
     <script type="text/javascript" src="../lib-scripts/jquery-1.10.2.min.js"></script> 
     <!-- script --> 
     <script type="text/javascript" src="plugin.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       $('#id-a').box({ name: 'aaaa' }); 
       $('#id-b').box({ name: 'bbbb' }); 
       $('#id-a').box('f'); 
       $('#id-b').box('f'); 
      }); 
     </script> 
    </head> 

    <body> 
     <div id="id-a"></div> 
     <div id="id-b"></div> 
    </body> 
</html> 

感谢

回答

3

两种方式,改变lambda函数的范围(与bind),或建立一个独立的参考变量,并把它放入closure

1:有绑定

$(this.element).fadeOut(1000, function() { 
    console.log(this.options.name);   // <- how do I access options.name? 
}.bind(this)); 

引用:

创建一个新的功能,当被调用时,将其关键字设置为 提供的值,并且在调用新函数时提供的任何 之前的给定序列参数。

OR

2:作为封闭

var that = this; 
$(this.element).fadeOut(1000, function() { 
    console.log(that.options.name);   // <- how do I access options.name? 
}); 

引用:

闭包是指独立的(自由)的变量的功能。在 之后,来自封闭父函数的变量仍然与父级范围相关联 。

另请参阅What is the scope of variables in JavaScript?

相关问题