- js中继承有几种方式,下面介绍4种,分别是prototype、call、apply、bind
- 一、prototype(原型)
//通过将父对象的构造函数的实例放在子对象的原型中,实现继承。
//原型继承
function person(name,age,sex,job){
this.name=name;
this.age=age;
this.sex=sex;
this.job=job;
}
person.prototype={
say(){
console.log("我们人都会说话");
},
eat(){
console.log("我们人都会吃饭");
},
}
function father(){
this.name="刘备";
}
father.prototype=new person("刘邦",60,"男","皇上");
let son=new father();
son.name="刘备";
console.log(son);
- 二、call
//将父对象的某一个方法暂时借给子对象,并且会立即执行
//将父对象的构造函数整个继承给子对象
//call继承
function father(){
this.name="动物";
this.say=function (a,b,c){
alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
};
}
function son(){
}
let dad=new father();
let sson=new son();
//call继承整个父对象
father.call(sson);
sson.say("一只狗",18,"狗");
//call继承父对象的一个属性或方法
dad.say.call(sson,"一只猫",18,"猫");
- 三、apply
//用法与call相同
//不同的是apply传递参数的时候将参数放在一个数组中传递;call会将参数一个一个用逗号隔开进行传
//apply继承
function father(){
this.name="动物";
this.say=function (a,b,c){
alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
};
}
function son(){
}
let dad=new father();
let sson=new son();
//apple继承整个父对象
father.apply(sson);
sson.say("一只猫",18,"猫");
//apple继承父对象的一个属性或方法
dad.say.apply(sson,["一只猫",18,"猫"]);
*四、bind
//bind用法于call,apply相同,不同的是bind不能继承整个构造函数。bind的继承结国会返回函数本身,不会立即执行
//bind符合我们正常的需求,可以将继承来的方法保存,当需要使用的时候再进行调用
function father(){
this.name="动物";
this.say=function (a,b,c){
alert("我是"+a+",我今年"+b+"岁了,我是最聪明的"+c)
};
}
function son(){
}
let dad=new father();
let sson=new son();
let a=dad.say.bind(sson);
a("一只猫",18,"猫")