learn-js icon indicating copy to clipboard operation
learn-js copied to clipboard

第十二天:不用 new

Open sofish opened this issue 9 years ago • 0 comments

一、避免无须有的实例化

一直很喜欢 Bootstrap 里用不 new 执行 js 的方式,写一个例子,阻止页面上任何 a[preventdefault] 标签的默认行为,并弹出它的链接:

(function($) {
  $(document).on('click', 'a[preventdefault]', function(e) {
    e.preventDefault();
    alert(this.href)
  });
})(jQuery);

这种方式不需要像 new PreventDefault('a[preventdefault]'),在 html 中直接声明,比如 Tab 插件,只需要写 data-toggle="Tab" data-target="#someId" 即可(新版好像已经不需要这样),而不像大家习惯的 new Tab('#id'),在不需要任何 options 的情况也能省就省,直接把 html 的标记当声明。当然,见仁见智,这种方式只是我自己比较喜欢。

二、类似于 jQuery 的 $.fn.pluginName 自助实例化

在 #13 中的注释也写了,$.fn === $.prototype ,为什么 $(selector).pluginName() 就可以直接用呢?有没有办法去掉 new 关键词呢?

function C(name) {
  // node 里可以用 !new.target 来检测
  if(!(this instanceof C)) return new C(name);
  this.name = name || 'noname';
}

C.prototype.test = function() {
  return 'i\'m ' + this.name;
}

var c = C();

console.log(c.name, c.test());

再一次,这也是见仁见智的事,我就不是很喜欢不 new 的情况,但实现 jQuery 的 $.fn 却又很喜欢。

sofish avatar Apr 26 '16 16:04 sofish