javascript - Douglas Crockford says we should use that=this. So why do some JS developers disagree? -


if watch enough douglas crockford videos on youtube, you'll see outer this stuff like

var = this;  $('p').each(function(){     that._textpieces.push($(this).text()); }); 

which why same. yet know js developers consider shoddy , instead use bind , other ways use more language features , yet make code more unreadable because reader has go more work figure out this means in exact context in used.

first off: several commenters have noted, it's preferred use .bind() in es5 , arrow functions in es6.

there once dark age before .bind(), evidenced the compatibility table @ bottom of mdn page; crockford of age. can see .bind() polyfill (also on mdn page), rolling own completely standards-correct .bind() non-trivial compared simple var = this; - it's not unreasonable latter.

of course, i'm not crockford, have no idea thought process way when :)

with in mind, trick come in handy on occasion. example, d3 has selection.each() function, called each element in selection element bound this. var = this; in outer scope here allows me access both element , outer scope this:

var = this; d3.selectall('circle.foo')   .each(function(d, i) {     var circle = d3.select(this);     var position = that.computeposition(circle);     circle       .attr('cx', position.x)       .attr('cy', position.y);   }); 

(this particular example cribbed code didn't want call computeposition() twice, there enough circle.foo dom nodes profiling had shown computeposition() bottleneck. can imagine similar scenarios in jquery , other such dom manipulation libraries.)

personally, call that bit more visually distinct this (e.g. context, outercontext, outerthis, etc.) minimize confusion.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -