對象、原型

問題1: OOP 指什么?有哪些特性

Object Oriented Programing,即面向?qū)ο蟪绦蛟O(shè)計(jì),其中兩個最重要的概念就是類和對象,類只是具備了某些功能和屬性的抽象模型,而實(shí)際應(yīng)用中需要一個一個實(shí)體,也就是需要對類進(jìn)行實(shí)例化,類在實(shí)例化之后就是對象。

  • 特性
  1. 繼承性:子類自動繼承其父級類中的屬性和方法,并可以添加新的屬性和方法或者對部分屬性和方法進(jìn)行重寫。繼承增加了代碼的可重用性。

  2. 多態(tài)性:子類繼承了來自父類中的屬性和方法,并對其中部分方法進(jìn)行重寫。

  3. 封裝性:將一個類的使用和實(shí)現(xiàn)分開,只保留部分接口和方法與外部聯(lián)系。

問題2: 如何通過構(gòu)造函數(shù)的方式創(chuàng)建一個擁有屬性和方法的對象?

可通過如下的代碼來創(chuàng)建:

Function Person(name,age){
  this.name = name
  this.age = age
}

Person.prototype.sayName = function(){
  console.log('I am ' + this.name)
}

問題3: prototype 是什么?有什么特性

1.在JavaScript中,每個函數(shù)都有prototype這個屬性,對應(yīng)的值是原型對象
2.每個對象都有內(nèi)部屬性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('前端');
原型鏈圖

問題5: 創(chuàng)建一個 Car 對象,擁有屬性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(this.name + 'is running')
    }

    Car.prototype.getStatus = function(){
        console.log(this.status)
    }

問題6: 創(chuàng)建一個 GoTop 對象,當(dāng) new 一個 GotTop 對象則會在頁面上創(chuàng)建一個回到頂部的元素,點(diǎn)擊頁面滾動到頂部。擁有以下屬性和方法

  1. ct屬性,GoTop 對應(yīng)的 DOM 元素的容器
  2. target屬性, GoTop 對應(yīng)的 DOM 元素
  3. bindEvent 方法, 用于綁定事件
  4. createNode 方法, 用于在容器內(nèi)創(chuàng)建節(jié)點(diǎn)
    function GoTop(ct){
        this.ct = ct
        this.createNode()
        this.bindEvent()

    }

    GoTop.prototype.bindEvent = function(){
        this.target.addEventListener('click',function(){
            document.body.scrollTop = 0
        })
    }
    GoTop.prototype.createNode = function(){
        this.target = document.createElement('div')
        this.target.innerText = 'GoTop'
        this.target.style.position = 'fixed'
        this.target.style.bottom = '20px'
        this.target.style.right = '100px'
        this.target.style.padding = '10px'
        this.target.style.color = 'white'
        this.target.style.borderWidth = '2px'
        this.target.style.borderColor = 'white'
        this.target.style.borderStyle = 'solid'
        this.target.style.cursor = 'pointer'
        this.ct.append(this.target)
    }
    new GoTop(document.body)

預(yù)覽鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容