代码之家  ›  专栏  ›  技术社区  ›  Michael Stum

jquery插件选项:在此之前或在此内部扩展。每个块?

  •  3
  • Michael Stum  · 技术社区  · 15 年前

    我正在看插件创作文章 http://docs.jquery.com/Plugins/Authoring 并在“默认值和选项”部分中看到了这个示例:

    $.fn.tooltip = function( options ) {  
    var settings = {
      'location'         : 'top',
      'background-color' : 'blue'
    };
    return this.each(function() {        
      // If options exist, lets merge them
      // with our default settings
      if ( options ) { 
        $.extend( settings, options );
      }
    

    我不完全理解.extend调用为什么在这个.each块中?我的第一直觉是把它写为:

    $.fn.tooltip = function( options ) {  
    var settings = {
      'location'         : 'top',
      'background-color' : 'blue'
    };
    $.extend( settings, options || {} );
    
    return this.each(function() { 
    

    所以我把.extend调用移到了返回的上方(并用一个-我想这是有意义的)替换了丑陋的if。.

    这里有什么我看不见的吗?有什么奇怪的关闭相关的东西吗?如:全局修改设置与仅对该呼叫进行修改?(编辑:显然我不是- http://jsfiddle.net/fVSDH/ )

    1 回复  |  直到 15 年前
        1
  •  3
  •   jAndy    15 年前

    你说得对。

    扩展 settings jquery集合中每个元素的对象。

    也是你的 || {} 很标准,很有战斗力。

    var settings = $.extend({
       'location':          'top',
       'background-color':  'blue'
    }, options || {});
    

    是可以在这里进行的另一个优化。