問題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.繼承性:可以解決代碼復用,讓編程更加靠近人類思維。當多個類存在相同的屬性(變量)和方法時,可以從這些類中抽象出父類,在父類中定義這些相同的屬性和方法,所有的子類不需要重新定義這些屬性和方法,只需要通過繼承父類中的屬性和方法。
2.封裝性:封裝就是把抽象出來的數據和對數據的操作封裝在一起,數據被保護在內部,程序的其它部分只有通過被授權的操作(成員方法),才能對數據進行操作。
3.多態性:指一個引用(類型)在不同情況下的多種狀態。也可以理解成:多態是指通過指向父類的引用,來調用在不同子類中實現的方法。多態利于代碼的維護和擴展,當我們需要使用同一類樹上的對象時,只需要傳入不同的參數就行了,而不需要再new 一個對象。
問題2: 如何通過構造函數的方式創建一個擁有屬性和方法的對象?
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 的每個對象都繼承另一個對象,后者稱為“原型”(prototype)對象。只有null除外,它沒有自己的原型對象。每一個構造函數都有一個prototype屬性,這個屬性就是實例對象的原型對象。
問題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. 創建一個 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.創建一個 GoTop 對象,當 new 一個 GotTop 對象則會在頁面上創建一個回到頂部的元素,點擊頁面滾動到頂部。擁有以下屬性和方法
1. `ct`屬性,GoTop 對應的 DOM 元素的容器
2. `target`屬性, GoTop 對應的 DOM 元素
3. `bindEvent` 方法, 用于綁定事件
4 `createNode` 方法, 用于在容器內創建節點