Binding function to null

function f() {
  return this.x
}
f = f.bind(null)
f() // undefined
x = 1
f() // 1

I cannot find any page where it says that binding to null or undefined has no effect. Everywhere it is written that this becomes a link to the first argument of bind, exceptions are not mentioned. Can somebody provide a link to somewhere describing such behaviour?

Answers:

Answer

This behavior is different between strict mode and non-strict mode.

In non-strict mode, if you set thisArg to be null or undefined, this will be coerced to the global object (window).

In strict mode, this could be null, you will got an error.

function f() {
  'use strict';
  return this.x
}
f = f.bind(null)
f() // TypeError: Cannot read property 'x' of null
Answer

The way that f() is being called in your example (a simple call) "this" refers to the global object (window) unless bound to something else. Binding in non-strict mode will only work with a truthy value i.e. binding to null or undefined is ignored and "this" remains bound to window.

That's why the assignment of 1 to x (without var keyword x is global, i.e. window.x) causes the function to return 1. Annotating your example:

function f() {
  return this.x
}
f = f.bind(null) // no effect in non-strict mode
f() // returns window.x (undefined)
x = 1 // window.x = 1
f() // returns window.x (1)

Binding to something that is truthy works e.g.

function f () { return this.x };
var y = { x: 42 };
var z = f.bind(y);
z(); // 42

However if you use strict mode, a binding of null or undefined will take effect.

function f () { "use strict"; return this.x; }
var z = f.bind(null); z(); // TypeError: Cannot read property 'x' of null
z = f.bind(); z(); // TypeError: Cannot read property 'x' of undefined
z = f.bind({x:42}); z(); // 42
z = f.bind({x:"foo"}); z(); // "foo"
Answer

Link to the paragraph, where this effect is specified. The problem was, falsey this is replaced with global object not while binding, but at the moment of bound function call.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.