問題1: OOP 指什么?有哪些特性
面向?qū)ο缶幊?br>
特性: 把某個(gè)功能看成一個(gè)整體(對(duì)象)台颠,通過調(diào)用對(duì)象的某個(gè)方法來啟動(dòng)
功能定嗓。在用的時(shí)候不去考慮這個(gè)對(duì)象內(nèi)部的實(shí)現(xiàn)細(xì)節(jié),在去實(shí)現(xiàn)這個(gè)對(duì)象細(xì)節(jié)的時(shí)候不用管誰在調(diào)用注整。
面向?qū)ο蟮膶懛ú粌H更簡潔能曾,而且更可控。
問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對(duì)象?
舉列說明
// 第一種方法
function Person(nick, age) {
this.nick = nick;
this.age = age;
this.sayName = function() {
console.log(this.nick);
}
}
var p1 = new Person('Byron', 25);
// 第二種方法
function Person(nick, age){
this.nick = nick;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.nick);
}
var p1 = new Person();
p1.sayName();
// 1肿轨、創(chuàng)建類的實(shí)列寿冕,即p1={},這步是把一個(gè)空的對(duì)象的proto屬性設(shè)置為F.prototype
// 2、初始化實(shí)列椒袍。函數(shù)F被傳入?yún)?shù)并調(diào)用驼唱,關(guān)鍵字this被設(shè)定為該實(shí)列
// 3、返回實(shí)列
問題3: prototype 是什么驹暑?有什么特性
因?yàn)槿魏晤惖膒rototype屬性本質(zhì)上都是個(gè)類Object的實(shí)例玫恳。
我們通過函數(shù)定義了類辨赐,類(函數(shù))自動(dòng)獲得屬性prototype,
每個(gè)類的實(shí)例都會(huì)有一個(gè)內(nèi)部屬性__proto__
京办,指向類的prototype屬性掀序。 特性:
實(shí)列可以通過prop 訪問到其類型的prototype屬性,這就意味著類的prototype對(duì)象可以作為一個(gè)公共容器,供所有實(shí)列訪問惭婿。
能夠抽象重復(fù)的理由:
所有實(shí)列都會(huì)通過原型鏈引用到類型prototype
prototype相當(dāng)于特定類型所有實(shí)列都可以訪問到的一個(gè)公共容器
重復(fù)的東西移動(dò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)建一個(gè) Car 對(duì)象不恭,擁有屬性name、color财饥、status换吧;擁有方法run,stop钥星,getStatus.
// 創(chuàng)建一個(gè)Car對(duì)象
function Car() {
this.name = name;
this.color = color;
this.status = status;
}
Car.prototype = {
run: function() {
console.log('is running');
}
stop: function() {
console.log('is stoped');
}
getStatus: function() {
console.log(this.status);
}
}
var car1 = new Car('寶馬', 'red', 'good');
問題6: 創(chuàng)建一個(gè) GoTop 對(duì)象沾瓦,當(dāng) new 一個(gè) GotTop 對(duì)象則會(huì)在頁面上創(chuàng)建一個(gè)回到頂部的元素,點(diǎn)擊頁面滾動(dòng)到頂部打颤。擁有以下屬性和方法
-
ct
屬性暴拄,GoTop 對(duì)應(yīng)的 DOM 元素的容器 -
target
屬性, GoTop 對(duì)應(yīng)的 DOM 元素 -
bindEvent
方法编饺, 用于綁定事件
4createNode
方法乖篷, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
// 創(chuàng)建一個(gè)GoTop對(duì)象
function GoTop($ct, $target) {
this.$ct = $ct;
this.$target = $target;
this.bindEvent();
}
GoTop.prototype = {
bindEvent: function() {
this.createNode();
this.$ct.on('click', function() {
// this.scrollTop(0);
// console.log($(this).scrollTop());
$(window).scrollTop(0);
})
},
createNode: function() {
this.$target.css({
padding: 10,
background: 'red',
outline: 'none',
border: 'none',
})
this.$ct.append(this.$target);
$('body').append(this.$ct);
}
}
var $ct = $('<div class="wrap"></div>');
var $target = $('<button class="btn">GoTop</button>');
new GoTop($ct, $target);