[实例]演示区别箭头函数和常规函数的this值
作者:admin 时间:2022-5-10 13:38:1 浏览:this是JavaScript中常常用到关键字,但它在箭头函数和常规函数中是不同的,因此我们在使用时要知道this在箭头函数和常规函数中的区别,知道不同后,才能正确使用它。
箭头函数没有自己的this
与常规函数不同,箭头函数没有自己的this和参数绑定。相反,这些标识符像任何其他变量一样在词法范围内解析。让我们看一个简单的例子:
name ="Arrow function"
let me = {
name: "Regular function",
thisInArrow:() => {
console.log("Example of " + this.name); //无 'this' 绑定
},
thisInRegular(){
console.log("Example of " + this.name); //'this' 绑定
}
};
me.thisInArrow();
me.thisInRegular();
输出
Example of Arrow function
Example of Regular function
与常规函数不同,箭头函数没有自己的this。在箭头函数的情况下,this指的是在定义this箭头函数的环境中的this值(即“外部”箭头函数),并且在函数的整个生命周期中保持不变,并且始终绑定到在最近的非箭头父函数中。
让我们再看一个简单的例子:


在函数表达式的情况下,this指的是在createObject内部创建的对象,在箭头函数的情况下,this指的是createObject自身的this。
无论如何执行或在何处执行,箭头函数内部的 this 值始终等于外部函数的 this 值。换句话说,箭头函数可按词法解析 this,箭头函数没有定义自己的执行上下文。
在以下示例中,myMethod() 是箭头函数 callback() 的外部函数:
const myObject = {
myMethod(items) {
console.log(this); // logs "myObject"
const callback = () => {
console.log(this); // logs "myObject"
};
items.forEach(callback);
}
};
myObject.myMethod([1, 2, 3]); 输出

箭头函数 callback() 中的 this 值等于外部函数 myMethod() 的 this。
this 词法解析是箭头函数的重要功能之一。在方法内部使用回调时,要确保箭头函数没有定义自己的 this:不再有 const self = this 或者 callback.bind(this) 这种解决方法。
箭头函数没有自己的参数绑定
参数对象在箭头函数中不可用,但在常规函数中可用。
常规函数:
let myFunc = {
showArgs(){
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);输出
箭头函数
let myFunc = {
showArgs : ()=> {
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);输出
总结
本文通过实例介绍了箭头函数和常规函数的this值的区别,通过本文的学习,我们应该了解到箭头函数和常规函数的this值的不同之处,在使用中要正确处理。



