javascript - js中的super底层是怎么实现的?
本文介绍了javascript - js中的super底层是怎么实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
为什么我在控制台log(super)总是报错呢?
解决方案
应该是super
关键字只能在class
内部使用,外部直接调用就会出错,因为你根本不知道父类的构造函数是那个啊。它们只是语法糖而已,JavaScript仍然是基于原型的继承,super
本质上就是借用构造函数的一种表现形式,我们可以通过如下清楚看出来。
原始class
实现方式
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());
语法糖
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());
非常有意思的事:
一脸懵逼.jpg,哈哈哈哈,其实通过上面的比较也应该清楚为什么是这样,ES6class
真的是语法糖,甜到忧伤。
这篇关于javascript - js中的super底层是怎么实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文