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?
bind(null, playsound) , it creates and returns a new function, always receiving playsound as first argument and using global context (Because null is used as context), just like all regular functions use global context, when you call them without new operator and not using . call() or apply() with specific context.
bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Summary. The bind() method creates a new function, when invoked, has the this sets to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
You can explicitly create properties of the global context ( window ): function g() { window. someFunction = function() { console. log("hi!"); }; } g(); someFunction(); // "hi!"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With