javascript中的class

ES5 定義構造函數(shù)

通過構造函數(shù)加屬性,通過原型加方法:

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中的構造函數(shù):

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

實例的隱式原型 = 構造函數(shù)的顯式原型

ES5 繼承

將低級構造函數(shù)的原型賦值為高級構造函數(shù)的實例來實現(xiàn)繼承:

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

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

// 綁定原型,實現(xiàn)繼承
Dog.prototype = new Animal()

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

ES6 class 繼承

通過 extends 關鍵字和 super 方法實現(xiàn)繼承:

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。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • class的基本用法 概述 JavaScript語言的傳統(tǒng)方法是通過構造函數(shù),定義并生成新對象。下面是一個例子: ...
    呼呼哥閱讀 4,194評論 3 11
  • JavaScript面向對象程序設計 本文會碰到的知識點:原型、原型鏈、函數(shù)對象、普通對象、繼承 讀完本文,可以學...
    moyi_gg閱讀 821評論 0 2
  • 面向對象編程是用抽象方式創(chuàng)建基于現(xiàn)實世界模型的一種編程模式,主要包括模塊化、多態(tài)、和封裝幾種技術。對 JavaSc...
    吳佳浩閱讀 591評論 0 4
  • 繼承6種套餐 參照紅皮書,JS繼承一共6種 1.原型鏈繼承 核心思想:子類的原型指向父類的一個實例 Son.pro...
    燈不梨喵閱讀 3,251評論 1 2
  • Ah! Vanitas Vanitatum! Which of us is happy in this world...
    Hippocrene閱讀 610評論 0 0

友情鏈接更多精彩內容