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"
.bind(null)
in the first place? It seems like it's defeating the whole purpose of using.bind()
.x
which is not inside the scope off()
at all.