js实现继承的几种方法

近来一直在整理js的知识点,将js实现继承的几种方法分享出来。如有不足,欢迎大神们指正。

子类复制父类的属性和方法

function supFun(x,y){
this.X = x;
this.Y = y;
}
supFun.prototype.move = function(){
console.log(this.X);
}
function subFun(x,y){
var sup = new supFun(x,y);
for(var p in sup){
subFun.prototype[p] = sup[p];
}
}
var sub = new subFun(2,3);
sub.move();//2

使用原型链

function supFun(x,y){
this.X = x;
this.Y = y;
}
supFun.prototype.move = function(){
console.log(this.X);
}
function subFun(x,y){
supFun.call(this,x,y);
}
subFun.prototype = supFun.prototype;
var sub = new subFun(2,3);
sub.move();//2

使用ES6 extends实现class之间的继承

class supFun{
constructor(x,y){
this.X = x;
this.Y = y;
}
move(){
console.log(this.X);
}
}
class subFun extends supFun{
get mulity(){
return this.X*this.Y
}
}
var sub = new subFun(2,3);
console.log(sub.mulity);//6
sub.move();//2

使用ES6的Object.create()方法

function supFun(x,y){
this.X = x;
this.Y = y;
}
supFun.prototype.move = function(){
console.log(this.X);
}
function subFun(x,y){
supFun.call(this,x,y);
}
subFun.prototype = Object.create(supFun.prototype);
var sub = new subFun(2,3);
sub.move();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值