为什么 Typescript 箭头函数 属性 可以访问这个
Why does Typescript arrow function property has access to this
我想了解箭头函数的范围。我在 Angular 中实现了一个小程序,但我有点困惑。在下面的代码中,我不太明白为什么它会绑定到 TestComponent
export class TestComponent {
a: string = "Hello World";
myArrowFunction = () => {
console.log(this.a); //
}
constructor(){
myArrowFunction(); //output: "Hello World"
}
}
箭头函数没有自己的 this
,所以 this
绑定到父函数,对吗? myArrowFunction
属于 TestComponent
,所以 myArrowFunction
中的 this
应该是未定义的,但在上面的示例中 this
绑定到 TestComponent
为什么?
test = {
b: "Hello World",
foo: () => {
console.log(this.b);
}
}
test.foo(); //output: undefined
与上面的javascript代码有什么区别? this.b 未定义。
这是正常的,因为箭头函数 this 引用了上面的对象,所以你的实例。
//console.log(this)
class TestComponent {
myArrowFunction = () => {// function set in instance
console.log(this); //
}
myFunction() {// function set in prototype
console.log(this); //
}
constructor() {
this.a = "Hello World";
this.myArrowFunction(); //output: "Hello World"
}
}
function A() {
this.foo = () => { console.log(this) };// A instance
this.foo()
}
A.prototype.bar = () => { console.log(this) };// global
new A();
//const a = new TestComponent();
我想了解箭头函数的范围。我在 Angular 中实现了一个小程序,但我有点困惑。在下面的代码中,我不太明白为什么它会绑定到 TestComponent
export class TestComponent {
a: string = "Hello World";
myArrowFunction = () => {
console.log(this.a); //
}
constructor(){
myArrowFunction(); //output: "Hello World"
}
}
箭头函数没有自己的 this
,所以 this
绑定到父函数,对吗? myArrowFunction
属于 TestComponent
,所以 myArrowFunction
中的 this
应该是未定义的,但在上面的示例中 this
绑定到 TestComponent
为什么?
test = {
b: "Hello World",
foo: () => {
console.log(this.b);
}
}
test.foo(); //output: undefined
与上面的javascript代码有什么区别? this.b 未定义。
这是正常的,因为箭头函数 this 引用了上面的对象,所以你的实例。
//console.log(this)
class TestComponent {
myArrowFunction = () => {// function set in instance
console.log(this); //
}
myFunction() {// function set in prototype
console.log(this); //
}
constructor() {
this.a = "Hello World";
this.myArrowFunction(); //output: "Hello World"
}
}
function A() {
this.foo = () => { console.log(this) };// A instance
this.foo()
}
A.prototype.bar = () => { console.log(this) };// global
new A();
//const a = new TestComponent();