What side effects does the keyword 'new' have in JavaScript?

前端 未结 6 2058
忘了有多久
忘了有多久 2021-02-07 01:58

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.faste         


        
6条回答
  •  甜味超标
    2021-02-07 02:32

    Travis, I am the developer behind the Starter site.

    @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.

    Simply changing the command from

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

    to

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

    will appease JSLint as you have found.

    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 object is created (via new)
    2. The instance is attached to the DOM element using jQuery's data :$(el).data('FasterTrim', this)

    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.

    A little more background:

    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.

提交回复
热议问题