這個(gè)部分是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: 單個(gè)對象)
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ù)的繼承)
前三層
我這里分享下前三層的一點(diǎn)淺見枪芒,第四層我留待以后再探討。
1 單個(gè)對象
calc = {
add: function(x, y){
return x + y
}
}
console.log(calc.add(1, 3))
這個(gè)非常簡單直觀疗垛。
2 原型鏈
這個(gè)是js特立獨(dú)行的地方:
對象————>原型
代碼示例如下:
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擴(kuò)展了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í)抛丽。