ES6语法 学习笔记(七)类-继承

类-继承

ES5中的继承方式

  • 普通的继承方式
//父类
function Father(name) {
    this.name = name;
}
Father.prototype.showName function() {
    return `名字是:${this.name}`;
}

//子类
function Son(name,age) {
    Father.call(this,name);
    this.age = age;
}
Son.prototype = new Father();
Son.prototype.showAge = function() {
    return `年龄是:${this.age}`;
}

//调用
let person = new Son("qwe","12");
console.log(person.name,person.age);//qwe 12
console.log(person.showName());//名字是:qwe
  • 圣杯模式实现继承
var inherit = (function (){
    var F = function () {};
    return function (Target,Origin) {
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constuctor = Target;
        Target.prototype.uber = Origin.prototype;
    }
});

ES6中实现的继承

class Father {
    constructor(name) {
        this.name = name;
    }
    showName() {
        return `名字为:${this.name}`;
    }
    static showMale() {//静态方法
        console.log(`xxxxxx`);
    }
}

class Son extends Father{
    constructor(name,age){
        super(name);
        this.age = age;
    }
    showName() {
        super.showName();//调用父类的方法
        
    }
    showAge() {
        return `年龄是:${this.age}`;
    }
}

let person = new Son("asd",34);
console.log(person.showName(),person.showAge());//名字为:asd 年龄是:34
console.log(Son.showMale());//xxxxxx
  • 在子类中如果有函数名与父类一样的方法会重写父类的方法,通过super调用父类的方法后就不会重写,也可实现子类的方法。
  • 在方法前面加static后这个方法不会被实例继承,子类可以继承该方法

小练习

对方快实现拖拽

<div id="div1" class="box left">DIV1</div>
<div id="div2" class="box right">DIV2</div>
class Drag {
    constructor(id) {
        this.div = document.querySelector(id);
        this.disX = 0;
        this.disY = 0;
        this.init();
    }
    init() {
        this.div.onmousedown = function(e) {
            this.disX = e.clientX - this.div.offsetLeft;
            this.disY = e.clientY - this.div.offsetTop;

            document.onmousemove = this.Move.bind(this);
            document.onmouseup = this.Up.bind(this);

            return false;//阻止默认事件
        }.bind(this);
    }

    Move(e) {
        this.div.style.left = e.clientX - this.disX + 'px';
        this.div.style.top = e.clientY - this.disY + 'px';
    }

    Up() {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}

//设置拖拽不能越界
class allDrag extends Drag{
    Move(e){
        super.Move(e);
        
        if(this.div.offsetLeft <= 0){
            this.div.style.left = 0;
        }else if(this.div.offsetTop <= 0) {
            this.div.style.top = 0;
        }
    }
}
new Drag("#div1");
new allDrag("#div2");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boboj1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值