我正在尝试按照一些官方的best practices创建一个jQuery插件

(function($){

  var methods = {
    init : function( options ) {
      this.options = options;
    }
  , add_that: function (elem) {
      this.append(elem);
      return (this);
    }
  , add_this: function (elem) {
      return (methods.add_that(elem));
    }
  };

  $.fn.test = function (method) {
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' + method + ' does not exist on jQuery.test' );
    }
  };

})(jQuery);

我希望add_that方法能够将内容附加到匹配的元素上。
现在,从add_this调用此方法。
$('#test').test('add_this', $('<div />'));



为什么我不能从this访问插件(add_that)?

最佳答案

因为从add_this调用后,作用域已更改。请注意,原始调用使用Function.apply将调用范围限制为this

if ( methods[method] ) {
  return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}

因此,大概可以通过在方法中再次使用Apply来解决此问题:
add_this: function (elem) {
  return methods.add_that.apply(this,[elem]);
}

实时示例:http://jsfiddle.net/XaUHV/

09-30 16:32
查看更多