4 ms·
Looking at you Ember. Ugh! var controller = this; Every time!
by sergiotapia 12y ago
Looking at you Ember. Ugh!
var controller = this;
Every time!
- chris_wot 12y agoThey 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.
- chris_wot 12y agoUh, what's the reason for the downvote?
- oldmanjay 12y agoProbably because when you editorialize in your comment, you may get an adverse reaction.
- chris_wot 12y agoNot 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.
- coldtea 12y agoPerhaps that the reason for that is not some "bug" in JS?
- chris_wot 12y agoExcept 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/Reference/Global_Objects/Function/bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...