【一分钟JavaScript】实现继承

127 阅读1分钟

构造函数实现继续

function Parent(){
	this.name='parent';
}
Parent.prototype.say=function(){
	console.log(`I amd ${name}`)
}
function Child(){
	Parent.call(this);
	this.type='child';
}
var c=new Child();//Child {name: "parent", type: "child"}
c.say();//Uncaught TypeError: c.say is not a function

使用call改变this指向,调用 Parent,此时Parent指向Child。 只能继承父类的实例属性和方法,而不能继续原型属性/方法。

使用原型

function Parent(){
	this.name='parent';	
	this.items=[1,2,3];
}
function Child(){
	this.type='Child';
}
Child.prototype=new Parent();
var c1=new Child();
var c2=new Child();
c1.name='child';
console.log(c2.name);//parent
c1.items.push(4);
console.log(c2.items);//[1,2,3,4]

由于c1和c2和__proto__均指向同一个Parent.prototype,造成c1.items更改时,c2.items也被修改了。

组合方式

吸引上面的经验,那么就是结合两个方法实现继承

function Parent(){
	this.name='parent';	
	this.items=[1,2,3];
}
Parent.prototype.say=function(){
	console.log(`I am ${name}`);
}
function Child(){
	Parent.call(this);
	this.type='Child';
}
Child.prototype=new Parent();
var c1=new Child();
var c2=new Child();
c1.name='child';
console.log(c2.name);//parent
c1.items.push(4);
console.log(c2.items);//[1,2,3]