js继承的用法

继承

组合继承

组合继承实际就是构造函数继承+原型链继承

function Person(name,age,sex) {
  this.name=name;
  this.age=age;
  this.sex=sex;
}
Person.prototype.sayHi=function () {
  console.log("来啦");
};
function Student(name,age,sex,score) {
  //借用构造函数:属性值重复的问题
  Person.call(this,name,age,sex);
  this.score=score;
}
//改变原型指向----继承
Student.prototype=new Person();//不传值
Student.prototype.constructor = Student
Student.prototype.eat=function () { console.log("没错"); };

缺点:

由于调用了两次父类,所以产生了两份实例

优点:

函数可以复用

不存在引用属性问题

可以继承属性和方法,并且可以继承原型的属性和方法

 

寄生组合继承-修复组合继承的不足。

function Person(name,age,sex) {
  this.name=name;
  this.age=age;
  this.sex=sex;
}
Person.prototype.sayHi=function () {
  console.log("来啦");
};
function Student(name,age,sex,score) {
  //借用构造函数:属性值重复的问题
  Person.call(this,name,age,sex);
  this.score=score;
}

let Link = function(){}
Link.prototype = Person.prototype
Student.prototype = new Link()
Student.prototype.constructor = Student
Student.prototype.eat=function () {
  console.log("没错");
};

 

es6类的继承

简单易理解

let d1 = document.querySelector(".d1");
let d2 = document.querySelector(".d2");


class Dra{
    constructor(ele) {
        this.ele = ele
    }
    downFn(){
        this.ele.onmousedown = e=>{
            let x,y
            let ev = e || window.event;
            console.log(ev.clientX,ev.clientY)
            x = ev.clientX - this.ele.offsetLeft;
            y = ev.clientY - this.ele.offsetTop;
            this.moveFn(x,y)
        }
    }
    moveFn(x,y){
        this.ele.onmousemove = e=>{
            let ev = e || window.event
            let xx = e.clientX
            let yy = e.clientY
            this.setStyle(xx-x,yy-y)
            this.upFn()
        }
    }
    setStyle(x,y){
        this.ele.style.left = x+"px"
        this.ele.style.top = y+"px"
    }
    upFn(){
        this.ele.onmouseup= () =>{
            this.ele.onmousemove = ""
        }
    }
}

let dra = new Dra(d1)
dra.downFn()
let dra2 = new Dra(d2)
dra2.downFn()

class Limit extends Dra{
    constructor(ele) {
        super(ele)//函数
    }
    setStyle(x,y){
        x = x<0?0:x
        y = y<0?0:y
        super.setStyle(x,y)//对象
    }
}

let limit = new Limit(d2)
limit.downFn()

super(ele)函数

super.xx   对象

类Limit通过extends继承Dra类,constructor中必须调用super(ele)函数,在Limit中可以重写Dra中的方法,而且super对象中可以拿到Dra类的属性和方法。

继承可以很好的扩展一些类的功能。

posted @ 2021-01-16 17:37  JS-Feng  阅读(246)  评论(0编辑  收藏  举报