class中函数的this指向

韩小韩
2023-03-06 / 0 评论 / 2,908 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年04月19日,已超过378天没有更新,若内容或图片失效,请留言反馈。

定义一个基础的类

class Person {
    constructor(name = '杜恒') {
        this.name = name
    }
    speak() {
        console.log(this);
    }
}

将上面的类实例出一个对象p,并调用p的speak方法

const p = new Person()
p.speak() // Person {name: "杜恒"}

尝试将p实例对象身上的speak方法赋值给另一个变量进行调用

const test = p.speak
test() // undefined

打印undefind,因此上面的方法可以改写成如下

const test = function () {
    "use strict"
    console.log(this);
}
test() // undefined

1

评论 (0)

取消