Binding this and arguments
suggest changeWhen you take a reference to a method (a property that is a function), it does not remember the object it was read from. If the method uses this, a bare call will not see that object. In non-strict code this is the global object and the method may silently do the wrong thing. In strict mode this is undefined and the call usually throws.
You can use the .bind() method on a function to create a wrapper that includes the value of this and any number of leading arguments.
const monitor = {
threshold: 5,
check: function(value) {
if (value > this.threshold) {
this.display("Value is too high!");
}
},
display(message) {
alert(message);
}
};
monitor.check(7); // The value of `this` is implied by the method call syntax.
const badCheck = monitor.check;
badCheck(15); // Non-strict: this is the global object, so this.threshold is undefined and the comparison is false. Strict: this is undefined and the call throws.
const check = monitor.check.bind(monitor);
check(15); // this was explicitly bound, so the function works.
const check8 = monitor.check.bind(monitor, 8);
check8(); // The leading argument is bound to 8. Later arguments do not replace it.
When not in strict mode, a function uses the global object (window in the browser) as this, unless the function is called as a method, bound, or called with the method .call syntax.
window.x = 12;
function example() {
return this.x;
}
console.log(example()); // 12
In strict mode, this is undefined by default:
window.x = 12;
function example() {
"use strict";
return this.x;
}
console.log(example()); // TypeError: reading 'x' of undefined
Bind operator
The double-colon bind operator (::) was a proposal, not standard JavaScript. The :: lines below are a syntax error in current engines unless a transpiler rewrites them. Use Function.prototype.bind, call, or apply instead.
var log = console.log.bind(console); // long version
const log = ::console.log; // short version
foo.bar.call(foo); // long version
foo::bar(); // short version
foo.bar.call(foo, arg1, arg2, arg3); // long version
foo::bar(arg1, arg2, arg3); // short version
foo.bar.apply(foo, args); // long version
foo::bar(...args); // short version
This syntax allows you to write normally, without worrying about binding this everywhere.
Binding console functions to variables
const log = console.log.bind(console);
log('one', '2', 3, JSON.stringify([4]), JSON.stringify({5: 5}));
one 2 3 [4] {"5":5}
Why would you do that?
One use case is a custom logger when you choose the destination at runtime. require is Node CommonJS, and logToServer must already be defined:
const logger = require("appLogger");
const log = logToServer ? logger.log : console.log.bind(console);