一句话说清楚js中的this指向

43 阅读1分钟

总述

在JavaScript中,this的指向取决于函数的调用方式。以下是一些常见的情况:

  • 直接调用函数时,this指向全局对象或undefined
  • 使用对象.方法调用时,this指向对象本身。
  • DOM事件处理函数中,this指向事件处理对象。

特殊情况:

  • 箭头函数中,this在函数声明时确定,指向箭头函数定义位置的this
  • 使用bindapplycall可以手动绑定this

总结:this的指向在JavaScript运行时确定,取决于函数的调用方式。

函数调用方式影响this指向

对象方法调用

使用对象.方法调用时,this指向该对象。

const obj = {
    name: "obj",
    say() {
        console.log(this.name);
    },
};
obj.say(); // 输出: obj
const say = obj.say;
say(); // 输出: undefined

严格模式下的类方法

在严格模式下,类方法中的this如果未绑定,将指向undefined

class User {
    constructor(name) {
        this.name = name;
    }
    say() {
        console.log(this.name);
    }
}

const user = new User("class");
user.say(); // 输出: class
const userSay = user.say;
userSay(); // 报错: Cannot read property 'name' of undefined

直接调用函数

直接调用函数时,this指向全局对象或undefined(在严格模式下)。

function sayHello() {
    console.log(this.name);
}

const obj = {
    name: "obj",
    sayHello,
};

obj.sayHello(); // 输出: obj

扩展:在TypeScript中定义this指向

接口定义

在TypeScript中,可以在接口中明确指定this的类型。

interface IUser {
    name: string;
    sayHello: (this: IUser) => void;
}

const u: IUser = {
    name: "张三",
    sayHello() {
        console.log(this.name);
    },
};

u.sayHello(); // 输出: 张三
const sayHello = u.sayHello;
sayHello(); // 报错: The 'this' context of type 'void' is not assignable to method's 'this' of type 'IUser'.

类定义

在类方法中也可以明确指定this的类型。

class User {
    constructor(public name: string, public age: number) {
        this.name = name;
    }

    say(this: User) {
        console.log(this.name);
    }
}

通过上述示例,可以更好地理解this在不同调用方式下的指向规则和如何在TypeScript中明确指定this的类型。