【一分钟JavaScript】实现继承

构造函数实现继续

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]
复制代码

转载于:https://juejin.im/post/5d01e10ee51d455cd73ba078

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值