js继承---类继承法

时间:2022-01-29 22:39:04
//父类
function Aaa(name,sex,inter){
this.name = name;
this.sex = sex;
this.inter = [1,2,3];
}
Aaa.prototype.showName = function(name){
return name;
} //子类
function Bbb(){
Aaa.call(this);//继承父类属性
} /*
继承父类中的function方法:
F过渡方法 避免prototype重复
Bbb.prototype.constructor = Bbb; 将构造方法重新指向 Bbb
*/
//function F(){}
var F = function(){};
F.prototype = Aaa.prototype;
Bbb.prototype = new F();
Bbb.prototype.constructor = Bbb; //实例化父类
var b1 = new Aaa();
b1.inter.push(4);
console.log("实例化父类后给inter增加元素结果为:"+b1.inter.toString()); //实例化子类
var b2 = new Bbb();
b2.inter.push(5);
console.log("实例化子类后给inter增加元素结果为:"+b2.inter.toString());