Is setting var _ = this bad practice in javascript -
i looking through open source code other day , noticed used var _ = this; maintain reference original this. novice in javascript wondering if bad practice?
i have seen , used self = this, that = this, me = this, use of underscore makes code easier read in eyes. since in plugin i'm writing requires it's use often. eyes can focus on variable/function more easily.
now question how feel using _ = this;
here code referring to.
https://github.com/kenwheeler/slick/blob/master/slick/slick.js
the question here if need that.
let's suppose have object call lassing callback.
now variable _ have this:
function person( name ) { var _ = this; _.name = name; _.dog = new dog( "fido" ); _.dog.goeat( function() { // when dog finished eat _.gooutwithyourdog( ); } ); ... in case can same without use _.
function person( name ) { this.name = name; this.dog = new dog( "fido" ); this.dog.goeat( function() { // when dog finished eat this.gooutwithyourdog( ); }.bind(this) ); ... using bind can wrap function , use inside person object.
you can use closer bind, let callback function have context binded caller, can use person object. os usefull when have use callback events. better of use _ because use if need it.
function person( name ) { this.name = name; (function(person){ $( ... ).on( "click", function( e ) { var value = this.value; person.dosomestuffwiththevalue( value ); } ); })( );
Comments
Post a Comment