【JavaScript学习笔记】super关键字

super关键字在JavaScript中有着特定的使用场景,如在class的constructor、静态方法、实例方法及对象字面量方法中。它用于引用父类的属性和方法,确保在使用this之前调用父类的构造函数,并在方法调用中使用正确的上下文。super.speak()等同于Cat.prototype.speak.call(this),而super(name)则等同于Cat.prototype.constructor.call(this, name)或Cat.call(this, name)。" 114175306,10293576,使用HeaderForwarder自动转发HTTP请求报头,"['httpcline转发', '微服务', 'HTTP', 'ASP.NET Core']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:郑航
链接:https://www.zhihu.com/question/38292361/answer/105183980
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

super关键字只能够以指定的形式出现在以下地点,否则代码会出现SyntaxError,无法通过编译:class语句块内的constructor函数的定义内,例如:

class B extends A {
    constructor(){
        super()
    }
}

建立class时,当且仅当“使用了extends关键字并指定了constructor函数”,super关键字必须以super([arg1[, arg2… argN]])的形式使用一次
此时super([arg1[, arg2… argN]])相当于创建了一个对象,且以该对象为context调用extends关键字指示的函数(以new的形式),随后这个对象成为constructor函数的context。因此super([arg1[, arg2… argN]])必须出现在constructor函数内的第一个this关键字之前,否则会报“this is not defined”的ReferenceError。亦可以super . IdentifierName的形式出现(这就与是否使用了extends关键字无关了)。super.IdentifierName作为getter使用时,表示函数B的prototype属性对象的[[prototype]];super.IdentifierName作为setter使用时,super表示this;class语句块内的static函数的定义内,例如:

class B extends A {
    static foo {
        super.test1() // 相当于A.test1.call(this)
        console.log(super.test2 === A.test2)
    }
}

必须以super . IdentifierName的形式出现。super.IdentifierName作为getter时,super表示该函数B的[[prototype]](本例中B的[[prototype]]即A)。若通过super.IdentifierName()来调用函数,则此函数的相当于通过.call(this)调用。super.IdentifierName作为setter使用时,super表示this。class语句块内的一般方法(非static或constructor函数)的定义内,例如:

class B extends A {
    foo() {
        super.foo()
    }
}

必须以super . IdentifierName的形式出现。super.IdentifierName作为getter时,super表示该函数B的prototype属性对象的[[prototype]]。同样,若通过super.IdentifierName()来调用函数,则此函数的相当于通过.call(this)调用;super.IdentifierName作为setter使用时,super表示this。在对象字面量的方法的定义内,例如:

let a = {
    foo() {
        super.test()
    }
}

let b = {
    test() {
        console.log("I'm b.")
    }
}

Object.setPrototypeOf(a, b);
a.foo(); // "I'm b."

必须以super . IdentifierName的形式出现,super.IdentifierName作为getter时,super表示该对象的[[prototype]]。同样,若通过super.IdentifierName()来调用函数,则此函数的相当于通过.call(this)调用。super.IdentifierName作为setter使用时,super表示this。

作者:manxisuo
链接:https://www.zhihu.com/question/38292361/answer/102519991
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在ES6中,super关键字构成两种表达式(实际是三种形式,见12.3.5 The super Keyword) :
SuperProperty : super. IdentifierName
SuperCall : super Arguments
分别对应你问题中的两种形式,即第一种是取属性,第二种是作为函数调用。具体语意见规范。单说你例子中的情况:
super.speak() 相当于:Cat.prototype.speak.call(this)
super(name) 相当于:Cat.prototype.constructor.call(this, name)
或者Cat.call(this, name)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值