javascript - js中的super底层是怎么实现的?

查看:237
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆