簡單學(xué)Javascript的對象

這個部分是js最重要的部分,也是最難掌握的部分。最近看到一本書《Speaking Javascript》, 分四層講解,感覺很有效。

Chapter 17. Objects and Inheritance

There are several layers to object-oriented programming (OOP) in JavaScript:
Layer 1: Object-orientation with single objects (covered in Layer 1: 單個對象)
Layer 2: Prototype chains of objects (described in Layer 2: 原型鏈)
Layer 3: Constructors as factories for instances, similar to classes in other languages (discussed in Layer 3: 構(gòu)造函數(shù))
Layer 4: Subclassing, creating new constructors by inheriting from existing ones (covered in Layer 4: 基于構(gòu)造函數(shù)的繼承)

前三層

我這里分享下前三層的一點淺見,第四層我留待以后再探討。

1 單個對象

calc = {
    add: function(x, y){
        return x + y
    }
}

console.log(calc.add(1, 3))

這個非常簡單直觀。

2 原型鏈

這個是js特立獨行的地方:

對象————>原型

代碼示例如下:

calc2 = Object.create(calc)
calc2.sub = function(x, y){
    return x - y
}

console.log(calc2.add(1, 3))
console.log(calc2.sub(1, 3))

create方法建立了原型鏈的關(guān)系,calc2擴展了sub方法,也有繼承的意味,代碼也很容易理解吧。

3 構(gòu)造函數(shù)

構(gòu)造函數(shù)是很多書介紹的方式,稍微復(fù)雜一些

function Calc(){

}

Calc.prototype.add = function(x, y){
    return x + y
}

aCalc = new Calc()
console.log(aCalc.add(2, 3))

總結(jié)

  • 我更傾向于前兩種方式,簡單直觀。
  • 精熟學(xué)習(xí)法:對于困難的東西可以用分層的方法來學(xué)習(xí)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容