<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<script type="text/javascript">
/*组合继承(最常用的继承方式)
使用原型链实现对原型属性和方法的继承,而通过借用构造函数的方式实现对实例属性的继承。即保证了实例都有自己的属性,又确保了方法的复用*/
console.log("----------组合式继承------------");
function Person(name){
this.name=name;
this.tecnologys=["java","javascript"];
}
Person.prototype.sayName=function(){
console.log(this.name);
}
function Student(name,age){
//继承属性
Person.call(this,name);
this.age=age;
}
//继承方法
Student.prototype=new Person();
Student.prototype.constructor=Student;
Student.prototype.sayAge=function(){
console.log(this.age);
}
//test
var inst1=new Student("xx",18);
inst1.tecnologys.push("Html5");
inst1.sayName();
inst1.sayAge();
console.log(inst1.tecnologys);
var inst2=new Student("YY",19);
inst2.sayName();
inst2.sayAge();
console.log(inst2.tecnologys);
console.log("------------原型式继承--------------");
//原型式继承
function object(o){//o为被继承的对象
function F(){};
F.prototype=o;
return new F();
}
var per={
name:"MM",
friends:["XH","XM"]
};
var instper1=object(per);
instper1.name="mm";
instper1.friends.push("xh");
var instper2=object(per);
instper2.name="nn";
instper2.friends.push("xm");
console.log("instper2:"+instper2.friends);//XH,XM,xh,xm
console.log("-----------寄生式继承--------------");
//寄生式继承
function createAnother(obj){
var clone=object(obj);
clone.sayHi=function(){
console.log("Hi");
}
return clone;
}
var another1=createAnother(per);
console.log(another1.sayHi());
console.log("----------寄生组合式继承------------");
//寄生组合式继承(最有效的继承方式):主要是为了解决组合式继承调用两次超类型构造函数的问题
function inheritPrototype(subType,superType){
var proto=object(superType.prototype);
proto.constructor=subType;
subType.prototype=proto;
}
function SuperType(name){
this.name=name,
this.colors=["red","green"]
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
console.log(this.age);
}
var instSub=new SubType("gg",22);
instSub.sayName();//gg
instSub.sayAge();//22
</script>
</body>
</html>
JavaScript的几种继承方式
最新推荐文章于 2022-06-12 17:33:47 发布