3 ms·
Perhaps that the reason for that is not some "bug" in JS?
by coldtea 12y ago
Perhaps 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...