Open
Description
super关键词
一、原来super
不只是用在class
里,任何对象都可以使用。
1.1 语法规则
var obj1 = {
name: 'obj1',
method1() {
console.log('method 1');
console.log(`name: ${this.name}`)
}
}
var obj2 = {
name: 'obj2',
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
//method 1
// name: obj2
obj2.method2();
super
只是子对象访问原型属性的一种方式,并不是原型;- 对象通过
super
调用父对象方法的this
是子对象(这个原则);
//method 1
// name: obj2
obj2.method2();
//method 1
// name: obj1
obj2.__proto__.method1();
- 子对象通过
super
只能访问原型属性,但不能修改原型属性(这也是原则);
var obj2 = {
name: 'obj2',
method2() {
super.name = 'change' // 赋值失败
console.log(super.name) // “obj1”
super.method1();
}
}
super
必须以对象访问的性质存在,其他都是语法错误;
var obj2 = {
name: 'obj2',
method2() {
typeof super; // SyntaxError: 'super' keyword unexpected here
super.method1();
}
}
总结:对象中引入super
的目的是为了方便调用被子对象覆盖的父对象的方法,其他任何对父对象的操作都无法(也不准许)通过super
进行。
1.2 super的 polyfill
直接看Babel如何做的
Issues
- Babel中获取
_getPrototypeOf
判断唯一依赖Object.setPrototypeOf
?
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}