关键字"new"在JavaScript中有什么副作用?
我正在开发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.
我已经尝试过必应给了我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: 我使用入门jQuery插件生成器作为我的插件的模板,该模板中包含该代码
Update #2: I used the Starter jQuery plug-in generator as a template for my plug-in, which has that code in it.
特拉维斯,我是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:
- 创建新对象(通过新对象)
- 使用jQuery的
data
:$(el).data('FasterTrim', this)
将实例附加到DOM元素
- New object is created (via new)
- 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.