构造函数的扩展
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
扩展Man构造函数
Man.prototype.love = function() {
console.log(this.name + 'love')
}
jj.love()
构造函数的继承
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 内置对象的扩展 例:String
String.prototype.backwards = function () {
var out = ''
for (var i = this.length - 1; i >= 0; i--) {
//substr() 方法可在字符串中抽取从 开始 下标开始的指定数目的字符。
out += this.substr(i, 1)
}
return out
}
var str = 'I Love You'
console.log(str.backwards())
封装 : 封装是一种面向对象编程的一种能力,
表示把数据和指令隐藏到对象内部,其实现方法与其他语言有所不同
function Box(width, length, height) {
function volume(a, b, c) {
console.log('体积为' + a * b * c)
}
this.boxVolume = volume(width, length, height)
}
//调用结果
var box = new Box(3, 4, 5)
//1.
//box.volume(3, 4, 5) //错误:box.volume is not a function
//2.
box.boxVolume //正确: 体积为60
网友评论