JavaScript的構(gòu)造函數(shù)擴(kuò)展、繼承以及封裝

構(gòu)造函數(shù)的擴(kuò)展

function Man () {
    this.name = 'rr'
    this.age = 21
    this.workinfo = function () {
        console.log('IT')
    }
}
var jj = new Man()
console.log(jj.name)   //打印 rr
jj.workinfo()          //打印 IT

擴(kuò)展Man構(gòu)造函數(shù)

Man.prototype.love = function() {
    console.log(this.name + 'love')
}
jj.love()

構(gòu)造函數(shù)的繼承

function Pig() {
    this.eat = '飯'
    this.sleep = function () {
        console.log('sleep')
    }
}
function Dog() {
    this.play = function () {
        console.log('play')
    }
}

Dog 繼承 Pig

Dog.prototype = new Pig()
var dog = new Dog()
dog.sleep()
console.log(dog.eat)

JavaScript 內(nèi)置對象的擴(kuò)展 例:String

String.prototype.backwards = function () {
    var out = ''
    for (var i = this.length - 1; i >= 0; i--) {
        //substr() 方法可在字符串中抽取從 開始 下標(biāo)開始的指定數(shù)目的字符。
        out += this.substr(i, 1)
    }
    return out
}

var str = 'I Love You'
console.log(str.backwards())

封裝 : 封裝是一種面向?qū)ο缶幊痰囊环N能力,
表示把數(shù)據(jù)和指令隱藏到對象內(nèi)部,其實(shí)現(xiàn)方法與其他語言有所不同

function Box(width, length, height) {
    function volume(a, b, c) {
        console.log('體積為' + a * b * c)
    }
    this.boxVolume = volume(width, length, height)
}
//調(diào)用結(jié)果
var box = new Box(3, 4, 5)
//1.
//box.volume(3, 4, 5)   //錯(cuò)誤:box.volume is not a function
//2.
box.boxVolume           //正確: 體積為60
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容