問題1: OOP 指什么?有哪些特性
- OOP是Object-orientend programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of "this" or "self"). In OOP, computer programs are designed by making them out of objects that interact with one another. There is significant diversity of OOP languages, but the most popular ones are class-based, meaning that objects are instances of classes, which typically also determine their type. -- 來自 wiki
- OOP的特性:
1.繼承性:可以解決代碼復(fù)用伤极,讓編程更加靠近人類思維酬荞。當(dāng)多個(gè)類存在相同的屬性(變量)和方法時(shí),可以從這些類中抽象出父類畅买,在父類中定義這些相同的屬性和方法,所有的子類不需要重新定義這些屬性和方法细睡,只需要通過繼承父類中的屬性和方法谷羞。
2.封裝性:封裝就是把抽象出來的數(shù)據(jù)和對數(shù)據(jù)的操作封裝在一起,數(shù)據(jù)被保護(hù)在內(nèi)部,程序的其它部分只有通過被授權(quán)的操作(成員方法)湃缎,才能對數(shù)據(jù)進(jìn)行操作犀填。
3.多態(tài)性:指一個(gè)引用(類型)在不同情況下的多種狀態(tài)。也可以理解成:多態(tài)是指通過指向父類的引用嗓违,來調(diào)用在不同子類中實(shí)現(xiàn)的方法九巡。多態(tài)利于代碼的維護(hù)和擴(kuò)展,當(dāng)我們需要使用同一類樹上的對象時(shí)蹂季,只需要傳入不同的參數(shù)就行了冕广,而不需要再new 一個(gè)對象。
問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對象?
function People(name,age) {
this.name = name
this.age = age
}
People.prototype.work = function() {
console.log('我的名字是:' + this.name + '我今年' + this.age + '歲了')
}
var people01 = new People('Jack',18)
people01.work()
問題3: prototype 是什么偿洁?有什么特性
- JavaScript 的每個(gè)對象都繼承另一個(gè)對象撒汉,后者稱為“原型”(prototype)對象。只有null除外涕滋,它沒有自己的原型對象睬辐。每一個(gè)構(gòu)造函數(shù)都有一個(gè)prototype屬性,這個(gè)屬性就是實(shí)例對象的原型對象宾肺。
問題4:畫出如下代碼的原型圖
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('前端');
QQ截圖20171110191521.png
問題5. 創(chuàng)建一個(gè) Car 對象溯饵,擁有屬性name、color锨用、status丰刊;擁有方法run,stop黔酥,getStatus
function Car(name,color,status) {
this.name = name
this.color = color
this.status = status
}
Car.prototype = {
run: function() {
console.log('run')
},
stop: function() {
console.log('stop')
},
getStatus: function() {
console.log(this.status)
}
}
問題6.創(chuàng)建一個(gè) GoTop 對象藻三,當(dāng) new 一個(gè) GotTop 對象則會(huì)在頁面上創(chuàng)建一個(gè)回到頂部的元素,點(diǎn)擊頁面滾動(dòng)到頂部跪者。擁有以下屬性和方法
1. `ct`屬性棵帽,GoTop 對應(yīng)的 DOM 元素的容器
2. `target`屬性, GoTop 對應(yīng)的 DOM 元素
3. `bindEvent` 方法渣玲, 用于綁定事件
4 `createNode` 方法逗概, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)