問題1: OOP 指什么?有哪些特性
oop(全稱object-oriented programming)是面向?qū)ο蟪绦蛟O(shè)計(jì),是種具有對象概念的程序變成典范。
特征有封裝性,繼承,多態(tài)
封裝是將一個(gè)類和實(shí)現(xiàn)分開,只保留部分接口和方法與外部聯(lián)系
繼承是子類繼承其父類種的屬性和方法,并且可以添加新的屬性和方法。
多態(tài):子類繼承了父級類種的屬性和方法,并對其中部分方法進(jìn)行重寫
問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個(gè)擁有屬性和方法的對象?
function dog(name){
this.dogname=name;
this.say=function()
{
console.log(this.dogname);
}
}
var kok=new dog("kok");
kok.say();
問題3: prototype 是什么?有什么特性
prototype是原型,每個(gè)函數(shù)會(huì)自動(dòng)生成,prototype指向函數(shù)的原型對象,原型對象中的方法能夠被子類復(fù)用和共享,另外原型對象中有一個(gè)constructor屬性,這個(gè)屬性指向構(gòu)造函數(shù)。
當(dāng)使用構(gòu)造函數(shù)生成一個(gè)對象的時(shí)候,該對象就會(huì)自動(dòng)生成一個(gè)_ _ proto _ _屬性,這個(gè)屬性指向構(gòu)造函數(shù)的原型對象。
image.png
問題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('前端');
image.png
問題5: 創(chuàng)建一個(gè) Car 對象,擁有屬性name、color、status;擁有方法run,stop,getStatus
function Cargroup(name,color,status)
{
this.name=name;
this.color=color;
this.status=status;
}
Cargroup.prototype.run=function()
{
console.log("runing")
}
Cargroup.prototype.stop=function()
{
console.log("stop")
}
Cargroup.prototype.getstatus=function()
{
console.log(this.status);
}
var Car=new Cargroup("Mini",'red','stop');
Car.run();
問題6: 創(chuàng)建一個(gè) GoTop 對象,當(dāng) new 一個(gè) GotTop 對象則會(huì)在頁面上創(chuàng)建一個(gè)回到頂部的元素,點(diǎn)擊頁面滾動(dòng)到頂部。擁有以下屬性和方法
1. `ct`屬性,GoTop 對應(yīng)的 DOM 元素的容器
2. `target`屬性, GoTop 對應(yīng)的 DOM 元素
3. `bindEvent` 方法, 用于綁定事件
4 `createNode` 方法, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<style>
.box{
height:600px;
background:green;
}
.wrapper{
border:1px solid red;
position:fixed;
bottom:30px;
background:yellow;
left:50%;
}
</style>
<body>
<div class="box"></div>
<div class="wrapper">
</div>
<script>
function GotTop(ct)
{
this.ct=ct;
this.target=this.createNode(this.ct);
this.bindEvent('click')
}
GotTop.prototype.createNode=function(par){
var div=document.createElement('div');
div.innerText="回到頂部"
par.appendChild(div);
return div;
}
GotTop.prototype.bindEvent=function(event)
{
this.target.addEventListener(event,function(){
scrollTo(0,0);
});
}
var s=document.querySelector(".wrapper");
var f=new GotTop(s);
</script>
</body>
</html>
效果
https://jsbin.com/moredulema/1/edit?html,output
問題7: 使用木桶布局實(shí)現(xiàn)一個(gè)圖片墻
代碼:https://github.com/HappyXll/WEB-KNOWLEDGE/blob/master/cask-layout/casklayout2.html
image.png