OOP 指什么?有哪些特性
OOP:Object-oriented programming 的縮寫,即面向?qū)ο蟪绦蛟O(shè)計(jì),其中兩個(gè)最重要的概念就是類和對(duì)象。
類是具備了某些功能和屬性的抽象模型,實(shí)際應(yīng)用中需要的是一個(gè)個(gè)實(shí)體,也就是需要對(duì)類進(jìn)行實(shí)例化,類在實(shí)例化之后就是對(duì)象。-
特性:
- 繼承性:子類自動(dòng)繼承其父級(jí)類中的屬性和方法,并可以添加新的屬性和方法或者對(duì)部分屬性和方法進(jìn)行重寫,繼承增加了代碼的復(fù)用性,讓類與類之間產(chǎn)生了聯(lián)系,提供了多態(tài)的前提
- 多態(tài)性:子類繼承了來自父級(jí)類中的屬性和方法,并對(duì)其中部分方法進(jìn)行重寫。(比如函數(shù)的length和數(shù)組的length都繼承自對(duì)象但作用不同),提高了代碼的擴(kuò)展性和可維護(hù)性
- 封裝性:將一個(gè)類的使用和實(shí)現(xiàn)分開,隱藏對(duì)象的屬性和實(shí)現(xiàn)細(xì)節(jié),僅對(duì)外提供公共訪問方式,提高代碼復(fù)用性和安全性。
-
原則:
- 開閉原則:
對(duì)擴(kuò)展開放:應(yīng)用的需求改變時(shí)我們可以對(duì)模塊進(jìn)行擴(kuò)展,使其具有滿足改變的新行為
對(duì)修改封閉:對(duì)模塊行為進(jìn)行擴(kuò)展是,不必改變模塊的源碼或二進(jìn)制代碼 - 接口隔離:
不要依賴用不到的接口
- 開閉原則:
如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對(duì)象?
function People(name, age) {
this.name = name
this.age = age
this.sayName = function () {
console.log(this.name)
}
this.sayAge = function () {
console.log(this.age)
}
}
var female = new People('dot', 2)
console.log(female)//People { name: 'dot', age: 2, sayName: f, sayAge: f }
console.log(female.sayName())//dot
console.log(female.sayAge())//2
prototype 是什么?有什么特性
- 每個(gè)函數(shù)都有
prototype這個(gè)屬性,對(duì)應(yīng)值是原型對(duì)象 - 每個(gè)對(duì)象都有個(gè)內(nèi)部屬性
__proto__,每個(gè)實(shí)例的__proto__指向創(chuàng)建它的構(gòu)造函數(shù)的prototype - 一切函數(shù)都是由 Function 這個(gè)函數(shù)創(chuàng)建的,所以
Function.prototype === 被創(chuàng)建的函數(shù).__proto__ - 一切函數(shù)的原型對(duì)象都是由 Object 這個(gè)函數(shù)創(chuàng)建的,所以
Object.prototype === 一切函數(shù).prototype.__proto__
畫出如下代碼的原型圖
function People (name){
this.name = name;
this.sayName = function(){
console.log('my name is:' + this.name);
}
}
People.prototype.walk = function(){
console.log(this.name + ' is walking');
}
var p1 = new People('饑人谷');
var p2 = new People('前端');

面向?qū)ο笤蛨D
創(chuàng)建一個(gè) Car 對(duì)象,擁有屬性name、color、status;擁有方法run,stop,getStatus
function Car(name, color, status) {
this.name = name
this.color = color
this.status = status
this.run = function () {
if (this.status === 1) {
console.log('I am running')
}
}
this.stop = function () {
if (this.status === 0) {
console.log('I am stopped')
}
}
this.getStatus = function () {
console.log(this.status)
}
}
var myCar = new Car('Audi', 'black', '1')
myCar.getStatus()
創(chuàng)建一個(gè) GoTop 對(duì)象,當(dāng) new 一個(gè) GotTop 對(duì)象則會(huì)在頁面上創(chuàng)建一個(gè)回到頂部的元素,點(diǎn)擊頁面滾動(dòng)到頂部。擁有以下屬性和方法
-
ct屬性,GoTop 對(duì)應(yīng)的 DOM 元素的容器 -
target屬性, GoTop 對(duì)應(yīng)的 DOM 元素 -
bindEvent方法, 用于綁定事件 -
createNode方法, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
使用木桶布局實(shí)現(xiàn)一個(gè)圖片墻
參考資料: