JS对象继承的几种方式总结

今天学习了一下js的继承,js中的继承主要分四种,原型继承,构造函数继承,call/apply继承以及es6的extend继承。
1.原型继承:
原型继承主要利用js对象的prototype引用父类的构造函数来复制父类的方法。

//定义一个Person类
	 function Person(name){  
        this.name=name;  
    }  
	//打招呼
    Person.prototype.sayHello=function(){  
        alert("Hello,my name is "+this.name);  
    }  
	 
	//定义Man类,继承Person类
	function Man(name,age){
		this.name=name;
		this.age=age; 
	}
	Man.prototype=new Person();
	var man= new Man("隔壁老王",30);
	man.sayHello();

2.构造函数继承
子类中调用父类的构造函数,完成继承。

 //定义一个Person类
	 function Person(name){  
        this.name=name;  
		this.sayHello=function(){  
        alert("Hello,my name is "+this.name);  
		}  
    }  
 
	//定义Man类,继承Person类
	function Man(name,age){
		this.constructor=Person;
		this.constructor(name);
		this.age=age;
	}

	var man= new Man("隔壁老王",30);
	man.sayHello();

3.call/apply继承
利用call/apply方法调用父类构造函数实现继承

 //定义一个Person类
	 function Person(name){  
        this.name=name;  
		this.sayHello=function(){  
        alert("Hello,my name is "+this.name);  
		}  
    }  
 
	//定义Man类,继承Person类
	function Man(name,age){
		Person.call(this,name);
		this.age=age;
	}

	var man= new Man("隔壁老王",30);
	man.sayHello();

4.extends继承
使用ES6定义类的方法,类似java定义类的方式实现继承,注意部分浏览器不兼容 – –

'use strict';
     //定义一个Person类
	 class Person{  
	 //构造函数
        constructor(name){
			this.name=name;
		}
		sayHello(){
			alert("My name is"+this.name);
		}
    }  
	
	class Man extends Person{
		constructor(name,age){
			//调用父类构造函数
			super(name);
			this.age=age;
		}
		
	}

	var man= new Man("隔壁老王",30);
	man.sayHello();

欢迎分享本文,转载请保留出处:前端ABC » JS对象继承的几种方式总结

分享到:更多 ()

发表评论 0