JavaScript 绑定“ this”和参数
示例
当您引用JavaScript中的方法(属性是函数)时,它通常不记得它最初附加的对象。如果该方法需要引用该对象,this因为它将无法引用该对象,则调用它可能会导致崩溃。
您可以在函数上使用该方法来创建一个包装,该包装包含的值和任意数量的前导参数。.bind()this
var monitor = {
threshold: 5,
check: function(value) {
if (value > this.threshold) {
this.display("价值太高!");
}
},
display(message) {
alert(message);
}
};
monitor.check(7); //方法调用语法隐含了this的值。
var badCheck = monitor.check;
badCheck(15); // The value of `this` is window object andthis.thresholdis undefined, so value >this.thresholdis false
var check = monitor.check.bind(monitor);
check(15); //这个`this`的值被明确绑定,该函数起作用。
var check8 = monitor.check.bind(monitor, 8);
check8(); //在这里,我们也将参数绑定到“8”。不能重新指定。当不在严格模式下时,函数将全局对象(window在浏览器中)用作this,除非将该函数作为方法调用,绑定或使用方法.call语法调用。
window.x = 12;
function example() {
return this.x;
}
console.log(example()); //12默认情况下this为严格模式undefined
window.x = 12;
function example() {
"use strict";
return this.x;
}
console.log(example()); //未捕获的TypeError:无法读取未定义的属性“x”(…)绑定运算符
可以将双冒号绑定运算符用作上述概念的简化语法:
var log = console.log.bind(console); //长版 const log = ::console.log; //简洁版本 foo.bar.call(foo); //长版 foo::bar(); //简洁版本 foo.bar.call(foo, arg1, arg2, arg3); //长版 foo::bar(arg1, arg2, arg3); //简洁版本 foo.bar.apply(foo, args); //长版 foo::bar(...args); //简洁版本
此语法使您可以正常编写,而不必担心this到处绑定。