关于普通函数和箭头函数的this

箭头函数的作用以及函数的二义性

函数的两种作用

  1. 作为指令序列,直接调用
  2. 作为构造函数,使用new关键字创建实例对象

JS中的this

  • this作为全局上下位的一部分,仅在函数被调用时才创建
js 复制代码
// ❌ 错误理解sadasda'张三',
    this: '???',  // 这只是一个普通属性,不是 this
    thisValue: this  // 这里的 this 是全局对象,不是 obj
};

// ✅ 正确理解:this 是在函数执行时确定的
const obj2 = {
    name: '李四',
    sayName() {
        console.log(this.name);  // this 在执行时才绑定到 obj2
    }
};

obj2.sayName(); // '李四' - this 指向 obj2
  • 普通函数this的绑定时机:普通函数定义时 this 未绑定
ts 复制代码
function showThis() {
    console.log(this);
}

const obj1 = { name: 'obj1', show: showThis };
const obj2 = { name: 'obj2', show: showThis };

// 同样的函数,不同的调用方式,this 指向不同
obj1.show(); // { name: 'obj1', show: f }
obj2.show(); // { name: 'obj2', show: f }
showThis();  // window/global (严格模式 undefined)

// 证明:函数没有固定的 this
console.log(showThis === obj1.show); // true (同一个函数)
  • 箭头函数的this是在定义时决定的,在函数作用域内向上查找最近的普通函数并继承
ts 复制代码
const obj = {
    name: 'obj',
    fun1: function() {
        console.log(this.name) // 'obj'
        const fun1Inner = () => {
            console.log(this.name) // 定义时的作用域绑定,此时作用域时fun1,而fun1的this指向obj
        };
        fun1Inner();
    };
    fun2: () => {
        console.log(this.name) // 调用时因为obj是一个对象,对象没有this,此时this指向window,而window没有name属性,输出undefined
    }

}

obj.fun1(); 
// 输出两个obj
obj.fun2();
// 输出undefiner
相关推荐
触底反弹1 天前
🚀 手把手用 HTML5 Canvas 从零打造飞机大战游戏,代码全开源!
前端·javascript·canvas
DJ斯特拉1 天前
axios快速使用
开发语言·前端·javascript
智通1 天前
可取消的异步任务与 AbortController
javascript
Hilaku1 天前
AI 写代码越快,为什么 Code Review 越不能省?
前端·javascript·程序员
HjhIron1 天前
CSS 3D 世界:从盒子模型到三维空间动画
javascript·css
VidDown1 天前
显卡处理视频技术详解:从硬解码到 NVENC,GPU 如何让视频处理起飞?
javascript·编辑器·音视频·视频编解码·视频
代码不加糖1 天前
Proxy能够监听到对象中的对象的引用吗?
开发语言·前端·javascript
大家的林语冰1 天前
连 Markdown 都不放过,Rust 在前端基建杀疯了,万物皆可“锈化“!
前端·javascript·markdown
想吃火锅10051 天前
【前端手撕】instanceof
前端·javascript·原型模式
один but you1 天前
const和constexpr常量表达式
java·前端·javascript