call的使用方法,在es6没有extents继承属性之前用call借用父构造函数的继承属性

call的使用方法,在es6没有extents继承属性之前用call借用父构造函数的继承属性

1.call能改变this的指向, 父构造函数的函数名.call(改变this的指向,继承父构造函数的name,继承父构造函数的age)

function Father(name,age){
// this指向父构造函数的对象实例
this.name=name;
this.age=age
}
// 父构造函数的原型方法
Father.prototype.money=function(){
console.log('爸爸需要赚钱')
}
function Son(name,age){
// this指向子构造函数的对象实例
Father.call(this,name,age)
}
// 子构造函数获取父构造函数的方法
Son.prototype=new Father()//把父构造函数的实例赋值给子构造函数

// 如果利用对象的形式修改了原型对象,别忘了用constructor修改回来
Son.prototype.constructor=Son

// 子构造函数的原型方法
Son.prototype.exe=function(){
console.log("儿子需要考试")
}
var son=new Son('刘德华',30)
son.money()
son.exe()
console.log(son.name)

 

posted @ 2022-12-30 09:30  小闫的姑娘  阅读(17)  评论(0编辑  收藏  举报