Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active February 13, 2018 07:03
Show Gist options
  • Save dfkaye/bf90a377a5713c689f0bd27e72a957df to your computer and use it in GitHub Desktop.
Save dfkaye/bf90a377a5713c689f0bd27e72a957df to your computer and use it in GitHub Desktop.
// Arrow functions bind to the context they're defined in.
// inner context example
(new function() {
this.name = 'test';
return { test: () => { console.log(this) } };
}).test() // { name: "test" }
// global context example
var a = { method: () => { console.log(this === window) } }
a.method() // true
// Their context can't be overridden by call (or apply, or bind)
a.method.call({}) // true
// By contrast, real functions bind to the object they're invoked on
var c = { method: function() { console.log(this === window) } }
c.method() // false
// Applied to a null context, they bind to the global element again
c.method.apply(null) // true
// Applied to a non-null value, they bind to that value.
c.method.apply('') // false
// Some would argue with my choice of terms here, or argue that `this` is the problem, and
// that JavaScript should not be used an a object-oriented language, but only as a
// function-oriented language.
//
// Baloney. The problem is that `null` and `undefined` are accepted as valid values to `call`,
// `apply`, and `bind`, and further that function-oriented improvements to JavaScript are
// like pre-processors: they are pretend improvements (less typing! implicit returns!)
// that reduce our understanding of JavaScript as a function-oriented language.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment