let a = "global";
class C {
a = "inside class C";
func() {
console.log(this.a);
}
arrowFunc = () => {
console.log(this.a);
};
}
const c = new C();
c.func();
c.arrowFunc();
const { func, arrowFunc } = c;
func();
arrowFunc();
inside class C
inside class C
TypeError: Cannot read properties of undefined (reading 'a')
inside class C
class C {
a = 1;
constructor() {
this.method = this.method.bind(this); // 自动绑定 this
}
method() {
console.log(this.a);
}
}
const Foo = () => {};
// 不能用 new
const foo = new Foo(); // TypeError: Foo is not a constructor
// 不能访问 new.target
const bar = () => new.target; // SyntaxError: new.target expression is not allowed here
// 匿名函数
(function(a) {
return a + 100;
});
// 第1种:去掉 function 关键字,增加 =>
(a) => {
return a + 100;
};
// 第2种:去掉函数体的括号 {},去掉 return 关键字(隐含返回)
(a) => a + 100;
// 第3种:去掉参数的括号 ()
a => a + 100;
// 参数括号不能省
(a, b) => a + b + 100; // 多个参数
() => a + b + 100; // 没有参数
// {} 和 return 不能省:当函数体内有多条语句时
(a, b) => {
const chuck = 42;
return a + b + chuck;
};