問(wèn)題1: OOP 指什么?有哪些特性
面向?qū)ο缶幊?br>
特性: 把某個(gè)功能看成一個(gè)整體(對(duì)象),通過(guò)調(diào)用對(duì)象的某個(gè)方法來(lái)啟動(dòng)
功能。在用的時(shí)候不去考慮這個(gè)對(duì)象內(nèi)部的實(shí)現(xiàn)細(xì)節(jié),在去實(shí)現(xiàn)這個(gè)對(duì)象細(xì)節(jié)的時(shí)候不用管誰(shuí)在調(diào)用。
面向?qū)ο蟮膶?xiě)法不僅更簡(jiǎn)潔,而且更可控。
問(wèn)題2: 如何通過(guò)構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對(duì)象?
舉列說(shuō)明
// 第一種方法
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)建類(lèi)的實(shí)列,即p1={},這步是把一個(gè)空的對(duì)象的proto屬性設(shè)置為F.prototype
// 2、初始化實(shí)列。函數(shù)F被傳入?yún)?shù)并調(diào)用,關(guān)鍵字this被設(shè)定為該實(shí)列
// 3、返回實(shí)列
問(wèn)題3: prototype 是什么?有什么特性
因?yàn)槿魏晤?lèi)的prototype屬性本質(zhì)上都是個(gè)類(lèi)Object的實(shí)例。
我們通過(guò)函數(shù)定義了類(lèi),類(lèi)(函數(shù))自動(dòng)獲得屬性prototype,
每個(gè)類(lèi)的實(shí)例都會(huì)有一個(gè)內(nèi)部屬性__proto__,指向類(lèi)的prototype屬性。 特性:
實(shí)列可以通過(guò)prop 訪(fǎng)問(wèn)到其類(lèi)型的prototype屬性,這就意味著類(lèi)的prototype對(duì)象可以作為一個(gè)公共容器,供所有實(shí)列訪(fǎng)問(wèn)。
能夠抽象重復(fù)的理由:
所有實(shí)列都會(huì)通過(guò)原型鏈引用到類(lèi)型prototype
prototype相當(dāng)于特定類(lèi)型所有實(shí)列都可以訪(fǎng)問(wèn)到的一個(gè)公共容器
重復(fù)的東西移動(dòng)到公共容器里放一份就可以了
問(wèn)題4:畫(huà)出如下代碼的原型鏈
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('前端');

問(wèn)題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');
問(wèn)題6: 創(chuàng)建一個(gè) GoTop 對(duì)象,當(dāng) new 一個(gè) GotTop 對(duì)象則會(huì)在頁(yè)面上創(chuàng)建一個(gè)回到頂部的元素,點(diǎn)擊頁(yè)面滾動(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);