拿一个非常简单的 jQuery 插件样板:
var _defaults = {
  foo: false
};
function Plugin( settings ) {
  this.opts = $.extend( {}, _defaults, settings );
}
我有一个doSomething方法,只有在选项foo设置为时才能成功运行,并且在某个时候true可能还有其他方法,所以我在放置语句的位置上遇到了难题。首先我想:doSomething()if
Plugin.prototype = {
  doSomething: function() {
    // Do something that depends on foo
  },
  method: function() {
    ...
    if ( this.opts.foo ) { this.doSomething() }
  },
  method: function() {
    ...
    if ( this.opts.foo ) { this.doSomething() }
  }
};
但后来为了干燥,我决定这样做:
Plugin.prototype = {
  doSomething: function() {
    if ( this.opts.foo ) {
      // Do something that depends on foo
    }
  },
  method: function() {
    ...
    this.doSomething();
  },
  method: function() {
    ...
    this.doSomething();
  }
};
因此,现在可以利用的方法doSomething运行该函数,而不管它是否为空 if foois false。
所以我的问题是,什么是更好的方法?第二个更短,但它必须每次都查找该方法,即使它不一定只是为了运行一个空函数。那么第一个效率更高吗?
哦,是的,我知道这可能是微优化,人们会说不用担心,但我只是好奇......