問題1: OOP 指什么?有哪些特性
OOP即 Object-Oriented Programming,面向?qū)ο蟮某绦蛟O(shè)計。
其特性有三個:繼承、封裝和多態(tài)
- 繼承:子類自動繼承父級類中的屬性和方法,并可以添加新的屬性和方法或者對部分屬性進(jìn)行重寫。
- 封裝:確保組件不會以不可預(yù)期的方式改變其它組件的內(nèi)部狀態(tài);只有在那些提供了內(nèi)部狀態(tài)改變方法的組件中,才可以訪問其內(nèi)部狀態(tài)。每類組件都提供了一個與其它組件聯(lián)系的接口,并規(guī)定了其它組件進(jìn)行調(diào)用的方法。
- 多態(tài):不同對象的同一方法,可以有不同的表現(xiàn)
問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個擁有屬性和方法的對象?
function Car (name){
this.name = name
this.sayName = function(){
console.log('my car is:' + this.name)
}
}
Car.prototype.run = function(){
console.log(this.name + ' is running')
}
var car = new Car('奧拓')
console.dir(car)
car.run()
問題3: prototype 是什么?有什么特性
我們創(chuàng)建的每個函數(shù)都有一個prototype屬性,這個屬性是一個指針,指向一個對象,而這個對象的用途是包含可以由特定類型的所有實例共享的屬性和方法。如果按照字面意思來理解,那么prototype就是通過調(diào)用構(gòu)造函數(shù)而創(chuàng)建的那個對象實例的原型對象。
問題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('前端');

原型圖.png
問題5: 創(chuàng)建一個 Car 對象,擁有屬性name、color、status;擁有方法run,stop,getStatus
function Car(name,color,status){
this.name = name;
this.color = color;
ths.status = status;
}
Car.prototype = {
run: function(){
console.log("it's running!!")
}
stop: function(){
console.log("it's stopped")
}
getStatus: function(){
console.log(this.status)
}
}
問題6: 創(chuàng)建一個 GoTop 對象,當(dāng) new 一個 GotTop 對象則會在頁面上創(chuàng)建一個回到頂部的元素,點擊頁面滾動到頂部。擁有以下屬性和方法
1. `ct`屬性,GoTop 對應(yīng)的 DOM 元素的容器
2. `target`屬性, GoTop 對應(yīng)的 DOM 元素
3. `bindEvent` 方法, 用于綁定事件
4 `createNode` 方法, 用于在容器內(nèi)創(chuàng)建節(jié)點
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>回到頂部</title>
<style>
.ct {
height: 1200px;
}
</style>
</head>
<body>
<div class="ct">
</div>
<script>
function GoTop(ct){
this.ct = ct;
this.target = this.createNode();
ct.appendChild(this.target);
this.bindEvent(ct);
}
GoTop.prototype = {
bindEvent: function(){
this.target.addEventListener("click",function(){
document.body.scrollTop = 0
})
},
createNode: function(){
var target = document.createElement("button");
target.innerText = "回到頂部";
target.style.position = "fixed";
target.style.right = "50px";
target.style.bottom = "50px";
return target;
}
}
var ct = document.querySelector(".ct");
var goTop = new GoTop(ct);
</script>
</body>
</html>