JavaScript 中的关键字“new"有什么副作用?

我正在为 jQuery 开发一个插件,我收到了这个 JSLint 错误:

I'm working on a plug-in for jQuery and I'm getting this JSLint error:

Problem at line 80 character 45: Do not use 'new' for side effects.

(new jQuery.fasterTrim(this, options));

我没有太多运气找到有关此 JSLint 错误或 new 可能具有的任何副作用的信息.

I haven't had much luck finding info on this JSLint error or on any side effects that new might have.

我试过 谷歌搜索不要使用'新'来获得副作用."并得到 0 个结果.必应给了我 2 个结果,但它们都只是引用了 JSLint 源.希望这个问题会改变这一点.:-)

I've tried Googling for "Do not use 'new' for side effects." and got 0 results. Binging gives me 2 results but they both just reference the JSLint source. Hopefully this question will change that. :-)

更新 #1:以下是上下文的更多来源:

Update #1: Here's more source for the context:

  jQuery.fn.fasterTrim = function(options) {
    return this.each(function() {
      (new jQuery.fasterTrim(this, options));
    });
  };

更新 #2:我使用 Starter jQuery 插件生成器 作为我的插件的模板,其中包含该代码.

Update #2: I used the Starter jQuery plug-in generator as a template for my plug-in, which has that code in it.

推荐答案

Travis,我是 Starter 网站的开发者.

Travis, I am the developer behind the Starter site.

@Pointy 一针见血.以这种方式编写 Starter 代码的原因是因为我们确实需要一个新对象,我们只是不需要在那时存储对它的引用.

@Pointy hit the nail on the head. The reason the Starter code is written that way is because we do need a new object, we just don't need to store a reference to it at that point.

只需从

(new jQuery.fasterTrim(this, options)); 

var fT = new jQuery.fasterTrim(this, options);

会像你发现的那样安抚 JSLint.

will appease JSLint as you have found.

Starter 插件设置遵循 jQuery UI 模式,即在元素的 data 集中存储对对象的引用.这就是正在发生的事情:

The Starter plugin setup follows the jQuery UI pattern of storing a reference to the object in the data set for the element. So this is what is happening:

  1. 创建新对象(通过 new)
  2. 使用 jQuery 的 data 将实例附加到 DOM 元素:$(el).data('FasterTrim', this)
  1. New object is created (via new)
  2. The instance is attached to the DOM element using jQuery's data :$(el).data('FasterTrim', this)

返回的对象没有用处,因此没有var声明.我将考虑更改声明并清理输出以使 JSLint 开箱即用.

There is no use for the object that is returned, and thus no var declaration made. I will look into changing the declaration and cleaning up the output to pass JSLint out of the box.

更多背景知识:

使用 data 存储对象的好处是我们可以在以后随时通过调用访问该对象:$("#your_selector").data('FasterTrim').但是,如果您的插件不需要以这种方式在中间流中访问(意思是,它在一次调用中设置并且不提供未来交互),则不需要存储引用.

The benefit to storing the object using data is that we can access the object later at any time by calling: $("#your_selector").data('FasterTrim'). However, if your plugin does not need to be accessed mid stream that way (Meaning, it gets set up in a single call and offers no future interaction) then storing a reference is not needed.

如果您需要更多信息,请告诉我.

Let me know if you need more info.

相关文章