对其他回答不满意。截止2019/3/13,得票最高的回答在事实上是错误的。
=>
的简短版本是它是一种快捷方式,用于编写一个函数并将其绑定到当前的this
。
const foo = a => a * 2
实际上是一个快捷方式
const foo = function(a) { return a * 2; }.bind(this);
你可以看到所有被缩短的东西,我们不需要
function
,也不需要
return
,也不需要
.bind(this)
,甚至不需要大括号或圆括号。
一个稍微更长的箭头函数示例可能是:
const foo = (width, height) => {
const area = width * height;
return area;
};
展示了如果我们想要函数有多个参数,需要使用括号,如果我们想要写多个表达式,需要用大括号和明确的 return
。
理解 .bind
的部分非常重要,它是一个大主题。这与 JavaScript 中 this
的含义有关。
全部 函数都有一个隐含的参数叫做 this
。当调用一个函数时,如何设置 this
取决于该函数被调用的方式。
举个例子:
function foo() { console.log(this); }
如果您正常调用它
function foo() { console.log(this); }
foo();
this
将成为全局对象。
如果您处于严格模式
`use strict`;
function foo() { console.log(this); }
foo();
function foo() {
`use strict`;
console.log(this);
}
foo();
这将会是未定义的
您可以使用call
或apply
直接设置this
function foo(msg) { console.log(msg, this); }
const obj1 = {abc: 123}
const obj2 = {def: 456}
foo.call(obj1, 'hello');
foo.apply(obj2, ['hi']);
你也可以使用点运算符.
隐式地设置this
。
function foo(msg) { console.log(msg, this); }
const obj = {
abc: 123,
bar: foo,
}
obj.bar('Hola');
当你想将一个函数作为回调或监听器使用时,就会出现一个问题。你创建了一个类,并希望将一个函数指定为回调,以便访问该类的一个实例。
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click', function() {
console.log(this.name);
});
}
}
上述代码无法正常工作,因为当元素触发事件并调用函数时,
this
值将不是类的实例。解决该问题的一种常见方法是使用
.bind
。
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click', function() {
console.log(this.name);
}.bind(this);
}
}
因为箭头语法执行的是相同的操作,所以我们可以写成:
因为箭头语法执行的是相同的操作,所以我们可以这样写:
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click',() => {
console.log(this.name);
});
}
}
bind
实际上会创建一个新的函数。如果没有 bind
,你可以像这样自己创建:
function bind(functionToBind, valueToUseForThis) {
return function(...args) {
functionToBind.call(valueToUseForThis, ...args);
};
}
在没有展开运算符的旧版JavaScript中,它会是这样的:
function bind(functionToBind, valueToUseForThis) {
return function() {
functionToBind.apply(valueToUseForThis, arguments);
};
}
了解代码需要理解闭包,但简单来说,bind
会创建一个新函数,该函数始终使用绑定到它的this
值调用原始函数。由于箭头函数是bind(this)
的快捷方式,因此它们也会执行同样的操作。