News for hackers. Stuff that matters.
Re:A re-introduction to JavaScript by coldtea on Saturday May 09, 2015 @06:57PM (#9517996)
Perhaps that the reason for that is not some "bug" in JS?
Re:A re-introduction to JavaScript by chris_wot on Saturday May 09, 2015 @09:49PM (#9518440)
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...