問題1: OOP 指什么?有哪些特性
Object Oriented Programing,即面向?qū)ο蟪绦蛟O(shè)計,其中兩個最重要的概念就是類和對象,類只是具備了某些功能和屬性的抽象模型,而實際應(yīng)用中需要一個一個實體,也就是需要對類進行實例化,類在實例化之后就是對象。
- 特性
繼承性:子類自動繼承其父級類中的屬性和方法,并可以添加新的屬性和方法或者對部分屬性和方法進行重寫。繼承增加了代碼的可重用性。
多態(tài)性:子類繼承了來自父類中的屬性和方法,并對其中部分方法進行重寫。
封裝性:將一個類的使用和實現(xiàn)分開,只保留部分接口和方法與外部聯(lián)系。
問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個擁有屬性和方法的對象?
可通過如下的代碼來創(chuàng)建:
Function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayName = function(){
console.log('I am ' + this.name)
}
問題3: prototype 是什么?有什么特性
1.在JavaScript中,每個函數(shù)都有prototype這個屬性,對應(yīng)的值是原型對象
2.每個對象都有內(nèi)部屬性proto,這個屬性指向其構(gòu)造函數(shù)的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('前端');
原型鏈圖
問題5: 創(chuàng)建一個 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(this.name + 'is running')
}
Car.prototype.getStatus = function(){
console.log(this.status)
}
問題6: 創(chuàng)建一個 GoTop 對象,當 new 一個 GotTop 對象則會在頁面上創(chuàng)建一個回到頂部的元素,點擊頁面滾動到頂部。擁有以下屬性和方法
-
ct
屬性,GoTop 對應(yīng)的 DOM 元素的容器 -
target
屬性, GoTop 對應(yīng)的 DOM 元素 -
bindEvent
方法, 用于綁定事件 -
createNode
方法, 用于在容器內(nèi)創(chuàng)建節(jié)點
function GoTop(ct){
this.ct = ct
this.createNode()
this.bindEvent()
}
GoTop.prototype.bindEvent = function(){
this.target.addEventListener('click',function(){
document.body.scrollTop = 0
})
}
GoTop.prototype.createNode = function(){
this.target = document.createElement('div')
this.target.innerText = 'GoTop'
this.target.style.position = 'fixed'
this.target.style.bottom = '20px'
this.target.style.right = '100px'
this.target.style.padding = '10px'
this.target.style.color = 'white'
this.target.style.borderWidth = '2px'
this.target.style.borderColor = 'white'
this.target.style.borderStyle = 'solid'
this.target.style.cursor = 'pointer'
this.ct.append(this.target)
}
new GoTop(document.body)