that, self or me — which one to prefer in JavaScript?

前端 未结 3 935
挽巷
挽巷 2020-12-16 12:31

While coding JavaScript sometimes you store the reference of object this in a local variable for different purposes (to set proper scope, to help code obfuscato

3条回答
  •  时光取名叫无心
    2020-12-16 12:56

    Well personally I'm trying to get better at making the variable mean something a little more than "that thing I need later". Often you need those temporary variables in situations that get a little gnarly; there might be two or more layers of temporary this stashes to keep track of.

    Thus, for example in a jQuery setup, I might use something to note the element type that a temporary this stash should hold:

    $('form').each(function() {
      var $form = $(this);
      $form.find('input:checkbox').each(function() {
        var $checkbox = $(this);
        // ...
      });
    });
    

    Using the "$" prefix on the variables is a nice way to keep track of whether the object has been "jQuery-ized" or not :-)

提交回复
热议问题