一、OOP 指什么饭入?有哪些特性
OOP(Object-oriented-programming):面向?qū)ο缶幊蹋且环N計算機(jī)編程架構(gòu)肛真。OOP有三大特性:封裝圣拄、繼承、多態(tài)毁欣。
- 封裝
把方法的具體步驟隱藏起來,對外暴露一個接口供訪問岳掐。使用者無需關(guān)心其中的實(shí)現(xiàn)凭疮,只需直接調(diào)用。
- 繼承
一個類會有“子類”串述,子類會比父類更加具體化执解,會繼承父類的屬性和行為,也可以在此基礎(chǔ)上擴(kuò)展纲酗。
- 多態(tài)
多態(tài)是指由繼承而產(chǎn)生的相關(guān)的不同的類衰腌,其對象對同一消息會做出不同的響應(yīng)。
二觅赊、如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個擁有屬性和方法的對象?
function Person(name) {
this.name = name
this.personFnc = function () {
console.log(1)
}
}
const Jack = new Person('Jack')
三右蕊、prototype 是什么?有什么特性
在 JS 中吮螺, prototype 是一個 構(gòu)造函數(shù) / 類(Class)的共有 成員 / 屬性饶囚。在對象實(shí)例化之后,可以通過__proto__
(瀏覽器實(shí)現(xiàn)鸠补,非標(biāo)準(zhǔn))訪問這一共有屬性萝风,如:
function Person(name) {
this.name = name
}
Person.prototype.sayHi = function(){
console.log(this.name)
}
const Jack = new Person('Jack')
const Bob = new Person('Bob')
console.log(Jack.__proto__ === Person.prototype) //true
console.log(Jack.sayHi === Bob.sayHi) // true
四、畫出如下代碼的原型圖
題目
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('前端');
原型圖
prototype 里還有
constructor
紫岩。
五规惰、創(chuàng)建一個 Car 對象,擁有屬性name泉蝌、color歇万、status;擁有方法run梨与,stop堕花,getStatus
function Car(options) {
this.name = options.name
this.color = options.color
this.status = options.status
}
Car.prototype.getStatus = function () {
console.log('status')
}
Car.prototype.run = function () {
console.log('run')
}
Car.prototype.stop = function () {
console.log('stop')
}
var BMW = new Car({
name: '寶馬',
color: '#fff',
status: 'run'
})
六、創(chuàng)建一個 GoTop 對象粥鞋,當(dāng) new 一個 GotTop 對象則會在頁面上創(chuàng)建一個回到頂部的元素缘挽,點(diǎn)擊頁面滾動到頂部。擁有以下屬性和方法
1. `ct`屬性,GoTop 對應(yīng)的 DOM 元素的容器
2. `target`屬性壕曼, GoTop 對應(yīng)的 DOM 元素
3. `bindEvent` 方法苏研, 用于綁定事件
4. `createNode` 方法, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
function GoTop(options) {
this.ct = options.ct
this.createNode()
}
GoTop.prototype.bindEvent = function (type, listener, options) {
this.target.addEventListener(type, listener, options)
}
GoTop.prototype.createNode = function () {
const a = document.createElement('a')
a.href = '#top'
this.addStyle(a, {
position: 'fixed',
right: '20px',
bottom: '50px',
border: '1px solid #999',
padding: '10px'
})
this.ct.appendChild(a)
//target 在這
this.target = a
}
GoTop.prototype.addStyle = function (node, css) {
for (let key in css) {
node.style[key] = css[key]
}
}