Hacker News new | ask | show | jobs
by chris_wot 4054 days ago
Especially when you need to do something like:

  var that = this;
2 comments

That's not generally necessary in ES6 when you use "=>" to define functions. Javascript is getting better...
What happens when you nest anonymous functions? Would you have to use the arrow operator at every level?
It's really a minor criticism and I know ES6 resolves the issue :-)
Through bind of course, for the silly person who downvote me. Helps to have strict mode on. Happy to have educated you!
Looking at you Ember. Ugh!

    var controller = this;
    
Every time!
They have to. There's a bug in the JavaScript spec that makes you do this :-) they are perfectly correct in doing what they are doing, if they didn't then funny thing would start to happen. Sad, but true.
Uh, what's the reason for the downvote?
Probably because when you editorialize in your comment, you may get an adverse reaction.
Not the first to complain about this behaviour. In fact, if you run in strict mode now, ES5 requires you to use bind, call or apply - it won't box this to the global object but will return undefined.

Why do you think they decided to do this? Strict mode is to allow folks to transition their code to the new standard - and the new standard has made this decision to fix a flaw in JavaScript - it acknowledges its a hack to return the global object in this case.

So I'm less editorialising and more pointing out what is already known. Hope this helps.

Perhaps that the reason for that is not some "bug" in JS?
Except that for many, it is. If you extract a function in an object and allocate it to a global function, and that function calls on "this", then it's fairly obvious that the function cares about the object and not the "this" of the current scope.

It's why ES5 has bind to get around this.

Example from MDN [1]

  this.x = 9; 
  var module = {
    x: 81,
    getX: function() { return this.x; }
  };
  
  module.getX(); // 81
  
  var getX = module.getX;
  getX(); // 9, because in this case, "this" refers to the global object

  // Create a new function with 'this' bound to module
  var boundGetX = getX.bind(module);
  boundGetX(); // 81
To make the above example work without bind, you need to take a copy of the reference to this, And use that copy. Thus the kludge:

  var module = {
    x: 81,
    that: this,
    getX: function() { return that.x; }
  };
Of course, if you run in strict mode (ES5) the original example will return undefined, because you are now expected to specify this via call, apply or bind.

1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...