ES5實(shí)現(xiàn)class

20201230.jpg

身后有陰影,那是因?yàn)槊嫦蛱?/strong>

ES6中的class可以看作一個語法糖贷腕,es5其實(shí)都是可以做到的廷痘,新的class語法使其更符合面向?qū)ο缶幊潭?/p>

區(qū)別

  • 類必須使用new調(diào)用套耕,否則會報(bào)錯尘应。ES5的構(gòu)造函數(shù)是可以當(dāng)做普通函數(shù)使用的
  • 類的內(nèi)部所有定義的方法惶凝,都是不可枚舉的
  • 類的靜態(tài)方法也可以被子類繼承
  • 可以繼承原生的構(gòu)造函數(shù)
  • ES5是先新建子類的實(shí)例對象this,再將父類的屬性添加到子類上菩收,由于父類的內(nèi)部屬性無法獲取梨睁,導(dǎo)致無法繼承原生的構(gòu)造函數(shù)
  • ES6允許繼承原生構(gòu)造函數(shù)定義子類鲸睛,因?yàn)镋S6是先新建父類的實(shí)例對象this娜饵,然后再用子類的構(gòu)造函數(shù)修飾this,使得父類的所有行為都可以繼承

使用ES5模擬實(shí)現(xiàn)ES6的class

new操作符檢查函數(shù)

類必須使用new調(diào)用官辈,否則會報(bào)錯

function _checkType(obj, constructor) {
    if (obj instanceof constructor) {
        throw new TypeError('Cannot call a class as a function')
    }
}

內(nèi)部方法不可枚舉

function definePorperties (target, descriptions) {
    for (let descriptor of descriptions) {
        descriptor.enumerable = descriptor.enumerable || false

        descriptor.configurable = true

        if ('value' in descriptor) {
            descriptor.writable = true
        }

        Object.defineProperty(target, descriptor.key, descriptor)
    }
}

/**
 * 
 * @param {*} constructor 表示對應(yīng)的constructor對象
 * @param {*} protoDesc  class內(nèi)部定義的方法
 * @param {*} staticDesc  class內(nèi)部定義的靜態(tài)方法
 */
function _creatClass (constructor, protoDesc, staticDesc) {
    protoDesc && definePorperties(constructor.prototype, protoDesc)
    staticDesc && definePorperties(constructor, staticDesc)
    return constructor
}

真正的創(chuàng)建class

function _checkType(obj, constructor) {
    if (!(obj instanceof constructor)) {
        throw new TypeError('Cannot call a class as a function')
    }
}


function definePorperties (target, descriptions) {
    for (let descriptor of descriptions) {
        descriptor.enumerable = descriptor.enumerable || false

        descriptor.configurable = true

        if ('value' in descriptor) {
            descriptor.writable = true
        }

        Object.defineProperty(target, descriptor.key, descriptor)
    }
}

/**
 * 
 * @param {*} constructor 表示對應(yīng)的constructor對象
 * @param {*} protoDesc  class內(nèi)部定義的方法
 * @param {*} staticDesc  class內(nèi)部定義的靜態(tài)方法
 */
function _creatClass (constructor, protoDesc, staticDesc) {
    protoDesc && definePorperties(constructor.prototype, protoDesc)
    staticDesc && definePorperties(constructor, staticDesc)
    return constructor
}



const Foo = function () {
    function Foo(name) {
        _checkType(this, Foo) // 檢查是否是new調(diào)用
        this.name = name
    }

    _creatClass(Foo, [ // class內(nèi)部定義的方法
        {
            key: 'say',
            value: function () {
                console.log(this.name);
            }
        }
    ], [
        {
            key: 'say',
            value: function () {
                console.log('static say');
                console.log(this.name);
            }
        }
    ])
    return Foo
}()

這個時候直接調(diào)用Foo()


image.png

使用new 操作符之后


image.png

下面截圖可以看出say方法是不可枚舉的


image.png

下圖則可以看出靜態(tài)方法say也是不可枚舉的


image.png

實(shí)現(xiàn)繼承

  • 類的靜態(tài)方法也可被子類繼承
function _inherits(subClass, superClass) {
    if (typeof superClass !== 'function' && superClass !== null) {
        throw new TypeError('父類必須是函數(shù)且不為null')
    }

    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    })

    if (superClass) {
        Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass._proto_ = superClass
    }
}

使用父類的實(shí)例對象this

// 返回父類的this箱舞,若為null患膛,返回自身
function _possibleConstructorReturn(self, call) {
    if (!self) {
        throw new ReferenceError('this has not initialised - super() has not been called ')
    }

    return call && (typeof call === 'object' || typeof call === 'function') ? call : self

}

創(chuàng)建子類class

const Child = function (_parent) {
    _inherits(child, _parent) // 繼承父類原型上的屬性和靜態(tài)方法的繼承

    function Child(name, age) {
        _checkType(this, Child)

        // 先使用父類的實(shí)例對象this朋截,再返回
        const _this = _possibleConstructorReturn(this, (Child._proto_ || Object.getPrototypeOf(Child)).call(this, name))
        _this.age = age
        return _this
    }

    return Child
}(Foo)

執(zhí)行截圖,證明繼承成功了

image.png

image.png

完整代碼

function _checkType(obj, constructor) {
    if (!(obj instanceof constructor)) {
        throw new TypeError('Cannot call a class as a function')
    }
}


function definePorperties (target, descriptions) {
    for (let descriptor of descriptions) {
        descriptor.enumerable = descriptor.enumerable || false

        descriptor.configurable = true

        if ('value' in descriptor) {
            descriptor.writable = true
        }

        Object.defineProperty(target, descriptor.key, descriptor)
    }
}

/**
 * 
 * @param {*} constructor 表示對應(yīng)的constructor對象
 * @param {*} protoDesc  class內(nèi)部定義的方法
 * @param {*} staticDesc  class內(nèi)部定義的靜態(tài)方法
 */
function _creatClass (constructor, protoDesc, staticDesc) {
    protoDesc && definePorperties(constructor.prototype, protoDesc)
    staticDesc && definePorperties(constructor, staticDesc)
    return constructor
}



const Foo = function () {
    function Foo(name) {
        _checkType(this, Foo) // 檢查是否是new調(diào)用
        this.name = name
    }

    _creatClass(Foo, [ // class內(nèi)部定義的方法
        {
            key: 'say',
            value: function () {
                console.log(this.name);
            }
        }
    ], [
        {
            key: 'say',
            value: function () {
                console.log('static say');
                console.log(this.name);
            }
        }
    ])
    return Foo
}()


function _inherits(subClass, superClass) {
    if (typeof superClass !== 'function' && superClass !== null) {
        throw new TypeError('父類必須是函數(shù)且不為null')
    }

    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    })

    if (superClass) {
        Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass._proto_ = superClass
    }
}

// 返回父類的this踊赠,若為null肺魁,返回自身
function _possibleConstructorReturn(self, call) {
    if (!self) {
        throw new ReferenceError('this has not initialised - super() has not been called ')
    }

    return call && (typeof call === 'object' || typeof call === 'function') ? call : self

}

const Child = function (_parent) {
    _inherits(Child, _parent) // 繼承父類原型上的屬性和靜態(tài)方法的繼承

    function Child(name, age) {
        _checkType(this, Child)

        // 先使用父類的實(shí)例對象this电湘,再返回
        const _this = _possibleConstructorReturn(this, (Child._proto_ || Object.getPrototypeOf(Child)).call(this, name))
        _this.age = age
        return _this
    }

    return Child
}(Foo)

class中子類調(diào)用super()的區(qū)別

super這個關(guān)鍵字,既可以當(dāng)作函數(shù)使用,也可以當(dāng)作對象使用寂呛。在這兩種情況下怎诫,它的用法完全不同。

  • super作為函數(shù)調(diào)用時贷痪,代表父類的構(gòu)造函數(shù)幻妓。ES6 要求,子類的構(gòu)造函數(shù)必須執(zhí)行super函數(shù)劫拢。子類沒有寫constructor方法肉津,js引擎默認(rèn),幫你執(zhí)行constructor(){ super() }

  • super作為對象時舱沧,在普通方法中妹沙,指向父類的原型對象;在靜態(tài)方法中熟吏,指向父類初烘。

這里需要注意,由于super指向父類的原型對象分俯,所以定義在父類實(shí)例上的方法或?qū)傩陨隹穑菬o法通過super調(diào)用的。
ES6在繼承中強(qiáng)制要求缸剪,必須在子類調(diào)用super吗铐,因?yàn)樽宇惖膖his是由父類得來的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末杏节,一起剝皮案震驚了整個濱河市唬渗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌奋渔,老刑警劉巖镊逝,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異嫉鲸,居然都是意外死亡撑蒜,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進(jìn)店門玄渗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來座菠,“玉大人,你說我怎么就攤上這事藤树≡〉危” “怎么了?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵岁钓,是天一觀的道長升略。 經(jīng)常有香客問我微王,道長,這世上最難降的妖魔是什么品嚣? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任骂远,我火速辦了婚禮,結(jié)果婚禮上腰根,老公的妹妹穿的比我還像新娘激才。我一直安慰自己,他們只是感情好额嘿,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布瘸恼。 她就那樣靜靜地躺著,像睡著了一般册养。 火紅的嫁衣襯著肌膚如雪东帅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天球拦,我揣著相機(jī)與錄音靠闭,去河邊找鬼。 笑死坎炼,一個胖子當(dāng)著我的面吹牛愧膀,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播谣光,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼檩淋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了萄金?” 一聲冷哼從身側(cè)響起蟀悦,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎氧敢,沒想到半個月后日戈,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡孙乖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年浙炼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片的圆。...
    茶點(diǎn)故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡鼓拧,死狀恐怖半火,靈堂內(nèi)的尸體忽然破棺而出越妈,到底是詐尸還是另有隱情,我是刑警寧澤钮糖,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布梅掠,位于F島的核電站酌住,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏阎抒。R本人自食惡果不足惜酪我,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望且叁。 院中可真熱鬧都哭,春花似錦、人聲如沸逞带。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽展氓。三九已至穆趴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間遇汞,已是汗流浹背未妹。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留空入,地道東北人络它。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像歪赢,于是被迫代替她去往敵國和親酪耕。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評論 2 361

推薦閱讀更多精彩內(nèi)容