js继承方式

1.原型链继承

function A(firstName){
	this.firstName=firstName		
}
A.prototype.getFirstName=function(){
	console.log(this.firstName);
}
function B(lastName){
	this.lastName=lastName;
}
B.prototype=new A("远");
B.prototype.getLastName=function(){
	console.log(this.lastName);
}
var person=new B("方");
person.getFirstName();
person.getLastName();

缺点:由于所有的引用类型的原型的属性会被所有实例共享,所以没有办法在不影响所有对象实例的情况下,给父类型的构造函数传递参数。
2.借用构造函数继承

function A(firstName){
	this.firstName=firstName		
}
function B(lastName){
	A.call(this,"远");
	this.lastName=lastName;
}
var person=new B("方");
console.log(person.firstName);
console.log(person.lastName);

缺点:父类的方法会被创建多次
3.组合继承(原型链和借用构造函数组合)

function A(firstName){
	this.firstName=firstName		
}
A.prototype.getFirstName=function(){
	console.log(this.firstName);
}
function B(firstName,lastName){
	A.call(this,firstName)
	this.lastName=lastName;
}
B.prototype=new A();
A.prototype.constructor=B;
B.prototype.getLastName=function(){
	console.log(this.lastName);
}
var person=new B("远","方");
person.getFirstName();
person.getLastName();

组合继承的缺点:父类的构造器被调用了两次
4.寄生式继承

function A(original){
	var clone=Object(original);
	clone.getName=function(){
		console.log(this.name);
	}
	return clone;
}
var person={
	name:"远方",
};
var B=A(person);
B.getName();

5.寄生组合式继承

function object(o){
	function F(){}
	F.prototype=o;
	return new F();
}
function inheritPrototype(B,A){
	var prototype=object(A.prototype);
	prototype.constructor=B;
	B.prototype=prototype
}
function A(firstName){
	this.firstName=firstName		
}
A.prototype.getFirstName=function(){
	console.log(this.firstName);
}
function B(firstName,lastName){
	A.call(this,firstName)
	this.lastName=lastName;
}
inheritPrototype(B,A);
B.prototype.getLastName=function(){
	console.log(this.lastName);
}
var person=new B("远","方");
person.getFirstName();
person.getLastName();

6.class继承

class A{
	constructor(x,y){
		this.x=x;
		this.y=y;
	}
	print(){
		console.log(this.x)
	}
}
class B extends A{
	constructor(x,y,z){
		super(x,y);
		this.z=z;
	}
	m(){
		super.print();
	}
}
let num=new B(1,2,3);
num.m();//1
console.log(num instanceof A); //true
console.log(num instanceof B); //true

super()方法在这里相当于A.prototype.constructor.call(this);
作为函数时,super()只能在子类的构造函数之中,用在其他地方就会报错
super作为对象时,在普通方法中指向父类的原型对象,在静态方法中指向父类。

你可能感兴趣的:(JavaScript)