OOP 指什么曼玩?有哪些特性
面向?qū)ο缶幊蹋∣bject Oriented Programming僧凰,OOP掂榔,面向?qū)ο蟪绦蛟O(shè)計)继效,其中最重要的就是類和對象,類就像一張圖紙装获,而對象就是將圖紙上的內(nèi)容賦予一個變量
- 繼承性:子類自動繼承其父級類中的屬性和方法瑞信,并可以添加新的屬性和方法或者對部分屬性和方法進(jìn)行重寫。繼承增加了代碼的可重用性穴豫。
- 多態(tài)性:子類繼承了來自父級類中的屬性和方法凡简,并對其中部分方法進(jìn)行重寫逼友。
- 封裝性:將一個類的使用和實現(xiàn)分開,只保留部分接口和方法與外部聯(lián)系秤涩。
如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個擁有屬性和方法的對象?
function Cat(name){ this.name=nam; } Cat.prototype.say = function(){ console.log("this.name") } var dog = new Cat(“xiaoming”); dog.say();//xiaoming
prototype 是什么帜乞?有什么特性
- 每個函數(shù)都有prototype這個屬性,對應(yīng)的值是原型對象
- 每個對象都有個內(nèi)部屬性 proto,這個屬性指向prototype屬性
用構(gòu)造函數(shù)創(chuàng)建出來的對象實例也是對象筐眷,其proto指向構(gòu)造函數(shù)的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('前端');
創(chuàng)建一個 Car 對象黎烈,擁有屬性name、color匀谣、status照棋;擁有方法run,stop武翎,getStatus
var Car = function(name,color,status){ this.name = name; this.color = color; this.status = status; } Car.prototype.run = function(){ console.log(“1”) } Car.prototype.stop = function(){ console.log(“1”) } Car.prototype.getStatus = function(){ console.log(“1”) } var mycar = new Car("瑪莎拉蒂"烈炭,“銀色”,888)后频;
創(chuàng)建一個 GoTop 對象梳庆,當(dāng) new 一個 GotTop 對象則會在頁面上創(chuàng)建一個回到頂部的元素,點擊頁面滾動到頂部卑惜。擁有以下屬性和方法
-
ct
屬性膏执,GoTop 對應(yīng)的 DOM 元素的容器 -
target
屬性, GoTop 對應(yīng)的 DOM 元素 -
bindEvent
方法露久, 用于綁定事件
4createNode
方法更米, 用于在容器內(nèi)創(chuàng)建節(jié)點
var GoTop = function(ct){ this.ct = ct; this.target = $(' <button>'+'點我回到頂部'+'</button>') } GoTop.prototypy.createNode = function(){ this.ct.append(this.target) } GoTop.prototypy.bindEvent = function(){ this.target.on('click',function(){ $(window).animate({scrollTop: 0},500); }) } var go = new GoTop; go.createNode(); go.bindEvent();