浅谈super如何实现

应该是super关键字只能在class内部使用,外部直接调用就会出错,因为你根本不知道父类的构造函数是那个啊。它们只是语法糖而已,JavaScript仍然是基于原型的继承,super本质上就是借用构造函数的一种表现形式,我们可以通过如下清楚看出来。

原始的class实现方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
}
function Child(name, age) {
//借用构造函数
Parent.call(this, name);
this.age = age;
}
//实现继承
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.getAge = function(){
return this.Age;
};
var people = new Child("lily", 20);
console.log(people.getName());

语法糖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
getAge() {
return this.age;
}
}
const people = new Child("lily", 20);
console.log(people.getName());
© 2018 Qing的前端开发Blog All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero