構(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