js面向对象之继承

186 阅读1分钟

继承的6种方法

1. 对象冒充

2. 原型链继承

//父类构造函数
var Parent = function(){
	this.name = 'mike';
	this.sayHi = function(){
		console.log(this.name);
	}
}
//子类构造函数
var Children = function(){}

//重写children的原型,此处children的constructor指向了parent
Children.prototype = new Parent();

var p = new Parent();
var c = new Children();
p.sayHi();
c.sayHi();
console.log(Children.prototype);

打印得:Children.prototype就是Parent()

3. 使用 call 或 apply 方法

通过改变了 this 的指向而实现继承,可实现赋值

//父类构造函数
var Parent = function(name){
	this.name = name;
	this.sayHi = function(){
		console.log(this.name);
	}
}
//子类构造函数
var Children = function(name){
	Parent.call(this,name);	//this指向children,并赋值

	this.getName = function(){
		console.log(this.name);
	}
}
//实例化对象并传参
var p = new Parent('mike');
var c = new Children('john');
c.sayHi();
console.log(Children.prototype);

打印得 Children.prototype,即Parent.prototype

4. 混合方式

//父类构造函数
/*var Parent = function(name){
	this.name = name;
}
Parent.prototype.sayHi = function(){
		console.log(this.name);
	}
//子类构造函数
var Children = function(name,age){
	//this指向children,并赋值
	//继承属性
	Parent.call(this,name);	
	this.age = age;
}
//重写children的原型
//继承方法
Children.prototype = new Parent();
//增加方法
Children.prototype.getAge = function(){
		console.log(this.age);
}

var p = new Parent('john');
var c = new Children('miek',30);
c.sayHi();
c.getAge();
console.log(Children.prototype);

打印得

Parent.call(this,name);使子构造函数继承了父构造函数的属性,但是Children.prototype = new Parent();这里没有给Parent赋值,所以name是undefined

5. 使用 Object.create 方法

//父类构造函数
/*var Parent = function(name){
	this.name = name;
}
Parent.prototype.sayHi = function(){
	console.log(this.name);
	}
//子类构造函数
var Children = function(name,age){
	//this指向children,并赋值
	//继承属性
	Parent.call(this,name);	
	this.age = age;
}
//把Parent的原型覆盖到Children的原型上
Children.prototype = Object.create(Parent.prototype);
//把constructor修改回指向Children
//Children.prototype.constructor = Children;

Children.prototype.getAge = function(){
	console.log(this.age);
}

var p = new Parent('john');
var c = new Children('miek',30);
c.sayHi();
c.getAge();
console.log(Children.prototype);

6. extends 关键字实现继承

es6实现继承

class Parent{
	constructor(name,age){
		this.name = name;
		this.age = age;
	}
}
class Children extends Parent{
	constructor(name,age,job){
		this.job = job; //此处会报错
		super(name,age);
		this.job = job;
	}
}
//实例化并赋值
var c = new Children('mike',30,'student');

console.log(Children.prototype);

Children的constructor指向Children