js实现继承的几种方法

来源:互联网 发布:淘宝卖家退货怎么同意 编辑:程序博客网 时间:2024/04/29 09:10
近来一直在整理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();