JavaScript对象函数

JavaScript对象函数,javascript,Javascript,我有一个JavaScript对象,定义如下: const测试={ myFirstFunction:()=>{ log('MyFirstFunction called'); this.mySecondFunction('data'); }, mySecondFunction:(参数)=>{ log('MySecondFunction调用'+param'); } }; test.myFirstFunction()箭头函数没有自己的此,它默认指向父此 在您的myFirstFunction&mySec

我有一个JavaScript对象,定义如下:

const测试={
myFirstFunction:()=>{
log('MyFirstFunction called');
this.mySecondFunction('data');
},
mySecondFunction:(参数)=>{
log('MySecondFunction调用'+param');
}
};

test.myFirstFunction()
箭头函数没有自己的
,它默认指向父

在您的
myFirstFunction&mySecondFunction
窗口中,父项是
窗口
。调用
时,this.mySecondFunction()
实际上是在查找不存在的
窗口.mySecondFunction()
。这就是它抛出错误的原因

将其更改为正常功能,它将正常工作

const测试={
myFirstFunction:function(){
log('MyFirstFunction called');
this.mySecondFunction('data');
},
mySecondFunction:函数(参数){
log('MySecondFunction调用'+param');
}
};

test.myFirstFunction()
箭头函数没有自己的
,它默认指向父

在您的
myFirstFunction&mySecondFunction
窗口中,父项是
窗口
。调用
时,this.mySecondFunction()
实际上是在查找不存在的
窗口.mySecondFunction()
。这就是它抛出错误的原因

将其更改为正常功能,它将正常工作

const测试={
myFirstFunction:function(){
log('MyFirstFunction called');
this.mySecondFunction('data');
},
mySecondFunction:函数(参数){
log('MySecondFunction调用'+param');
}
};
test.myFirstFunction()表示:

Arrow函数没有自己对“this”的绑定,应该 不能用作方法

箭头函数根据定义箭头函数的范围建立“此”

因此,在这种情况下,“this”将不是“test”对象。

表示:

Arrow函数没有自己对“this”的绑定,应该 不能用作方法

箭头函数根据定义箭头函数的范围建立“此”


因此,在这种情况下,“this”将不是“test”对象。

原因是箭头函数不绑定它们自己的
上下文,相反
仍将是
窗口


尝试
test.mySecondFunction('data')
取而代之

原因是箭头函数不绑定自己的
上下文,而
仍将是
窗口


尝试
test.mySecondFunction('data')
相反,箭头函数不绑定自己的this,而是从父作用域继承this(“词法作用域”)

因此,在常规函数中,默认情况下,作用域绑定到全局函数。另一方面,箭头函数没有自己的this,但它们从父作用域继承它(在本例中为全局作用域)

const测试={
myFirstFunction:function(){
log('MyFirstFunction called');
this.mySecondFunction('data');
},
mySecondFunction:函数(参数){
log('MySecondFunction调用'+param');
}
};

test.myFirstFunction()箭头函数不绑定自己的this,它们从父作用域继承this(“词法作用域”)

因此,在常规函数中,默认情况下,作用域绑定到全局函数。另一方面,箭头函数没有自己的this,但它们从父作用域继承它(在本例中为全局作用域)

const测试={
myFirstFunction:function(){
log('MyFirstFunction called');
this.mySecondFunction('data');
},
mySecondFunction:函数(参数){
log('MySecondFunction调用'+param');
}
};

test.myFirstFunction()
Fat arrow函数不会从调用站点接收
,而是从其周围范围接收。这是否回答了您的问题?Fat arrow函数不会从调用站点接收
,而是从其周围范围接收。这是否回答了您的问题?今天我学到了一些新东西。谢谢今天我学到了一些新东西。谢谢