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

this 指向2 — 类中的this

作者头像
用户9914333
发布2022-07-22 14:34:18
2570
发布2022-07-22 14:34:18
举报
文章被收录于专栏:bug收集

本文继续讨论 this 指向 问题,今天讨论:

类中的this

0 1

类上下文

this 在 类 中的表现与在函数中类似,因为类本质上也是函数,但也有一些区别和注意事项。

代码语言:javascript
复制
class Example{
     constructor(){
         this.eat=function(){
             console.log('go eatting!');
         }

    }
    rich(){
     console.log("I'm rich man!");
    }

    static drink(){
     console.log('drink water!');
    }
}

运行结果:

注:

通过static 关键字申明的方法,表示静态方法,实例对象是没有这个方法的,它是添加在类上面的。

通过:类名.方法名()调用

new 的过程:

this -> {}

{ age:18 }

{ age : 18, eat : function(){} }

return this;

注:通过this 添加的属性和方法,在实例对象上;其它方法都在this对象的原型链上,这是一个重点。

如下图:

0 2

派生类

派生类中写构造函数必须在super,否则报错, 如下

代码语言:javascript
复制
class Father{
        constructor() {
            this.age = 44 ;
        }
        swim(){
            console.log('go swimming !!!');
        }
}
class Son extends Father{
        constructor() {
        }
        eat(){
           console.log("eating ");
       }
}

报错:

Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

在类son中,添加super方法即可,如下

代码语言:javascript
复制
constructor() {
    super()
}

且注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()

如下代码,也会报错

代码语言:javascript
复制


constructor() {
    this.sex = '男';  
    super()
}

正确代码如下:

代码语言:javascript
复制
constructor() {
    super()
    this.sex = '男';  
}

0 2

constructor 中为啥要加super

super关键字用于访问和调用一个对象的父对象上的函数。

因为子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工,而 super 就代表了父类的构造函数。

super 虽然代表了父类 Father 的构造函数,但是返回的是子类 Son 的实例,即 super 内部的 this 指的是 Son.

因此 super() 在这里相当于

Father.prototype.constructor.call(this, props)。

代码语言:javascript
复制
class Son extends Father{
        constructor() {
            super();
            this.sex = '男';  
        }
        eat(){
           console.log("eating ");
       }
}

如上代码中,super() 所做的工作

1. 调用了Fahter 的constructor

2. 生成this ,绑定Father中的属性(相当于new Father)

3. 返回Son的实例(即this)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-05-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 bug收集 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档