构造函数的封装 继承 多态
构造函数的封装
function aa(name){
this.name = name,
this.run=function(){
}
}
aa.prototype.age= 18
var b = new aa()
继承
面向对象编程思想,一般都是基于class类语法的,但是在ECSA6之前js没有class,我们使用 构造函数来替代
function aa(name){
this.name = name,
}
aa.prototype = {
run:function(){ alert(this.name+'会跑')},
eat:function(){
alert(this.name+"会吃")
}
}
function bb(name,color){
aa.call(this,{ //构造函数的伪装
//call 方法是改变 aa函数的 this 指向的, 指向第一个参数
name:name,
color:color
})
}
//1原型链 ,继承父一级的方法
//使用遍历的形式继承原型里面的东西,这样不会影响到父级的原型
for(var a in aa.prototype){
bb.prototype[a] = aa.prototype[a]
}//注意不要直接赋值 bb.prototype = aa.prototype
//2 bb.prototype = Object.create(aa.prototype)
//3调用构造函数写法 aa.prototype = new aa()
var bb2 = new bb('张三','绿色')
bb.prototype = aa.prototype
不提倡 因为这个是通过赋值的形式拿过来的,bb原型修改会影响他的父级 aa原型的内容
如果 aa 有d多个子集呢?所以这种方法不合适
多态
function aa(name){
this.name = name;
this.run=function(){
console.log(this.name+'会跑')
}
}
//通过原型的方式添加 eat 方法,
// a = new aa() b=new aa() 原型属性和方法,这些对象共用的
aa.prototype.eat=function(){
alert(this.name+'爱吃跳跳糖')
}
var zhangsan = new aa('张三')
// zhangsan.eat()
//函数aaPlus 继承 函数 aa
function aaPlus(name,color){
//通过伪装this,原型不会被继承到
aa.call(this,name)
this.color=color
}
//继承父级的原型,属性和方法
for(var i in aa.prototype){
aaPlus.prototype[i] = aa.prototype[i]
}
var lisi = new aaPlus('李四','green')
// 对象想改变原型 使用 __proto__
//函数改变原型 prototype
lisi.__proto__.eat=function(){
alert(this.name+"爱吃"+this.color+"颜色的棒棒糖")
}
lisi.run()
lisi.eat()
zhangsan.eat()
还没有评论,来说两句吧...