我在几个地方读过,关键的区别是" this在箭头函数中是词法绑定的".这一切都很好,但我实际上并不知道这意味着什么.
我知道这意味着它在定义函数体的大括号范围内是独一无二的,但我实际上无法告诉你以下代码的输出,因为我不知道所指的this是什么,除非它指的是胖箭头函数本身....这似乎没用.
var testFunction = () => { console.log(this) };
testFunction();
Run Code Online (Sandbox Code Playgroud) 在Angular中,在技术上可以将类方法编写为ES2015箭头函数,但我从未真正见过有人这样做过.以这个简单的组件为例:
@Component({
selector: 'sample'
})
export class SampleComponent {
arrowFunction = param => {
// Do something
};
normalFunction(param) {
// Do something
}
}
Run Code Online (Sandbox Code Playgroud)
这没有任何问题.有什么不同吗?为什么我应该或不应该使用它?
有没有理由编写ES6方法的经典语法?
class MyClass {
myMethod() {
this.myVariable++;
}
}
Run Code Online (Sandbox Code Playgroud)
当我myMethod()在某些事件上使用回调时,我必须写这样的东西(在JSX中):
// Anonymous function.
onClick={() => { this.myMethod(); }}
// Or bind this.
onClick={this.myMethod.bind(this)}
Run Code Online (Sandbox Code Playgroud)
但是如果我将方法声明为箭头函数:
class MyClass {
myMethod = () => {
this.myVariable++;
}
}
Run Code Online (Sandbox Code Playgroud)
我只能写(在JSX中):
onClick={this.myMethod}
Run Code Online (Sandbox Code Playgroud)