作者:郑航
链接: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)