前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(八)类中方法 this 的指向

(八)类中方法 this 的指向

作者头像
老怪兽
发布2023-02-22 19:47:07
1710
发布2023-02-22 19:47:07
举报

🐆类中方法 this 的指向

代码语言:javascript
复制
class Person {
    constructore(name, age) {
        this.name = name
        this.age = age
    }

    speck() {
        // speck 方法放在哪里? --- 类的原型对象上,供实例使用
        // 通过 person 实例调用 speck 时, speck 中的 this 就是 Person 的实例
        console.log(this)
    }

    const p1 = new Person('tom', 18)
    p1.speck()  // 通过实例调用 speck 方法
}

二、为什么把函数实例对象赋值给新变量,this 变成了 undefiend

代码语言:javascript
复制
class Person {
    constructore(name, age) {
        this.name = name
        this.age = age
    }

    speck() {
        // speck 方法放在哪里? --- 类的原型对象上,供实例使用
        // 通过 person 实例调用 speck 时, speck 中的 this 就是 Person 的实例
        console.log(this)
    }

    const p1 = new Person('tom', 18)
    p1.speck() // 通过实例调用 speck 方法
    const x = p1.speck  
    x()
}
  • p1.speck 属于实例调用,所有能读取到 this
代码语言:javascript
复制
p1.speck()
  • x 通过赋值拿到了 p1.speck 这个函数,然后通过 x() 去调用这个方法,称为直接调用,又应为使用了类,类中的函数,自动开启了严格模式,所以不允许 this 指向 window 所以 thisundefiend
代码语言:javascript
复制
const x = p1.speck  
x()  // 直接调用
函数是可以开启局部严格模式的 use strict
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年12月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 🐆类中方法 this 的指向
  • 二、为什么把函数实例对象赋值给新变量,this 变成了 undefiend
    • 函数是可以开启局部严格模式的 use strict
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档