js中super关键字的使用

super关键字可以使用于对象,也可在类中使用,下面分别来说

  • 对象
 let parent = {
    name: 'lili',
    getName(){
        console.log(this.name)
    }
}
let son = {
    name: 'mike',
    getName(){
        super.getName()
    }
}
Object.setPrototypeOf(son, parent)
son.getName() // 'mike'

可以看到对象中“方法”通过super关键字调用原型上的方法,this指向了对象本身

我们再来改造一下上面的对象

let son = {
    name: 'mike',
    getName(){
        console.log(super.name)
    }
}
Object.setPrototypeOf(son, parent)
son.getName() // 'lili'

我们发现,在对象的方法通过super关键字调用原型上的属性时,返回了原型的属性值(此时,没有用到this哈)

从上面我们有了结论:
super.name
等同于
Object.getPrototypeOf(this).name【属性】
等同于
Object.getPrototypeOf(this).name.call(this)【方法】

字面意思:
super.name指向的是原型对象上的name,但是绑定的this还是当前的son对象,
只要在对象的方法上通过super调用原型的方法,this指向当前的子类实例。

 class Parent {
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name)
    }
}
class Son extends Parent{
    constructor(name,age){
        this.age = age
        super(name)
    }
    getName(){
        super.getName()
    }
}
let son = new Son('mike', 18). // Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

在上面利用extends实现了类的继承,但是我们实例化子类的时候报错了,看报错信息,我们可以知道:子类没有自己的this对象,而是继承父亲的this对象,然后进行加工。如果不调用super,子类就得不到this对象

所以上面的代码,要先调用super,然后在对this进行操作.我们修改一下代码

class Parent {
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name)
    }
}
class Son extends Parent{
    constructor(name,age){
    	super(name)
        this.age = age
    }
    getName(){
        super.getName()
    }
}
let son = new Son('mike', 18)
son.getName() //mike

将super调用置于this之前,可以正常运行,上看是再有constructor方法的时候,那么,如果没有constructor那有如何呢?

class Parent {
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name)
    }
}
class Son extends Parent{}
let son = new Son('mike')
son.getName() //'mike'

发现在类的继承中,子类如果没有constructor方法,那么super调用会默认被添加到子类中,使得子类可以正常被初始化

上面的super对方法的调用时普通方法,那如果super调用的是静态方法呢?来试试添加一下静态方法吧

class Parent {
    constructor(name){
        this.name = name;
    }
    static sayHello(){
        console.log('hello')
    }
    getName(){
        console.log(this.name)
    }
}
class Son extends Parent{
    static testStatic(){
        super.sayHello()
    }
}
Son.testStatic(). // 'hello'

我们发现,在静态方法中使用super,那么这个super将指向父类本身,在普通方法中调用super,此时super将指向父类的原型对象

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值