javascript中的class

ES5 定义构造函数

通过构造函数加属性,通过原型加方法:

function MathHandle(x, y) {
    this.x = x;
    this.y = y;
}

MathHandle.prototype.add = function() {
    return this.x + this.y;
}

var m = new MathHandle(1, 2);
console.log(m.add());   // 3

ES6 Class语法

class MathHandle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
        
    add() {
        return this.x + this.y;
    }
}

var m = new MathHandle(1, 2);
console.log(m.add());   // 3

class 实际上是语法糖,编译后就是ES5中的构造函数:

typeof MathHandle;  // function
MathHandle === MathHandle.prototype.constructor;    // true
m.__proto__ === MathHandle.prototype  // true

实例的隐式原型 = 构造函数的显式原型

ES5 继承

将低级构造函数的原型赋值为高级构造函数的实例来实现继承:

// 动物
function Animal() {
    this.eat = function () {
        alert('Animal eat')
    }
}

// 狗
function Dog() {
    this.bark = function () {
        alert('Dog bark')
    }
}

// 绑定原型,实现继承
Dog.prototype = new Animal()

var hashiqi = new Dog()
hashiqi.bark()
hashiqi.eat()

ES6 class 继承

通过 extends 关键字和 super 方法实现继承:

class Animal {
    constructor(name) {
        this.name = name;
    }
    eat() {
        console.log(`${this.name} eat`);
    }
}

class Dog extends Animal {
    constructor(name) {
        super(name);
        this.name = name;
    }
    say() {
         console.log(`${this.name} say`);
    }
}

const hashiqi = new Dog("哈士奇");
hashiqi.eat();
hashiqi.say();

本质还是语法糖,使用 prototype。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 9,569评论 3 11
  • JavaScript面向对象程序设计 本文会碰到的知识点:原型、原型链、函数对象、普通对象、继承 读完本文,可以学...
    moyi_gg阅读 4,143评论 0 2
  • 面向对象编程是用抽象方式创建基于现实世界模型的一种编程模式,主要包括模块化、多态、和封装几种技术。对 JavaSc...
    吴佳浩阅读 3,561评论 0 4
  • 继承6种套餐 参照红皮书,JS继承一共6种 1.原型链继承 核心思想:子类的原型指向父类的一个实例 Son.pro...
    灯不梨喵阅读 8,384评论 1 2
  • Ah! Vanitas Vanitatum! Which of us is happy in this world...
    Hippocrene阅读 3,627评论 0 0

友情链接更多精彩内容