1: OOP 指什么甲馋?有哪些特性
OOP:Object-oriented programming,面向?qū)ο蟪绦蛟O(shè)計(jì),其中兩個(gè)最重要的概念就是類和對(duì)象。類只是具備了某些屬性和方法的抽象模型惰瓜,而實(shí)際運(yùn)用中需要一個(gè)一個(gè)實(shí)體,也就是需要對(duì)類進(jìn)行實(shí)例化汉矿,類在實(shí)例化后就是對(duì)象崎坊。
特性:
- 繼承性:子類自動(dòng)繼承父類中的屬性和方法,并可以添加新的屬性和方法洲拇。
- 多態(tài)性:子類可以對(duì)父類中部分方法進(jìn)行重寫奈揍。
- 封裝性:將一個(gè)類的使用和實(shí)現(xiàn)分開(kāi),只保留部分接口和方法與外部聯(lián)系
2: 如何通過(guò)構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對(duì)象?
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.showAge=function(){
console.log("姓名:"+this.name+" 年齡:"+this.age);
}
var person=new Person("高進(jìn)",24);
person.showAge();
3: prototype 是什么呻待?有什么特性
JavaScript的每個(gè)對(duì)象都繼承另一個(gè)對(duì)象,后者稱為“原型”(prototype)對(duì)象队腐。只有null除外蚕捉,它沒(méi)有自己的原型對(duì)象。原型對(duì)象上的所有屬性和方法柴淘,都能被派生對(duì)象共享迫淹。這就是JavaScript繼承機(jī)制的基本設(shè)計(jì)。通過(guò)構(gòu)造函數(shù)生成實(shí)例對(duì)象時(shí)为严,會(huì)自動(dòng)為實(shí)例對(duì)象分配原型對(duì)象敛熬。每一個(gè)構(gòu)造函數(shù)都有一個(gè)prototype屬性,這個(gè)屬性就是實(shí)例對(duì)象的原型對(duì)象第股。
每個(gè)函數(shù)都自動(dòng)添加一個(gè)名稱為prototype的屬性应民,這是一個(gè)對(duì)象。
每個(gè)對(duì)象都有一個(gè)內(nèi)部屬性proto(規(guī)范中沒(méi)有指定這個(gè)名稱夕吻,但是瀏覽器都這么實(shí)現(xiàn)的) 指向其構(gòu)造函數(shù)的prototype屬性诲锹,類的實(shí)例也是對(duì)象,其proto屬性指向“類”的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)建一個(gè) Car 對(duì)象归园,擁有屬性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(name+"run");
};
Car.prototype.stop=function(){
console.log(name+"stop");
};
Car.prototype.getStatus=function(){
console.log(this.name+this.status);
}
var car=new Car("法拉利","黃色","run");
car.getStatus();
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
方法, 用于綁定事件 -
createNode
方法形导, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
function GoTop(ct, target) {
this.ct = ct;
this.target = target;
this.createNode();
this.bindEvent();
}
GoTop.prototype.bindEvent = function () {
$("." + this.target).on("click", function () {
$(window).scrollTop(0);
})
}
GoTop.prototype.createNode = function () {
var node = "";
node += '<button class="' + this.target + '" >回到頂部</button>'
console.log(node);
this.ct.append($(node));
}
var goTop = new GoTop($(".box"), "btn");