难点记录

418 阅读1分钟

由于前端和后端的知识的侧重点感觉还是不一样的,有些点很难去理解,这是个人记录的对自己来说比较难以理解的地方。持更...

ES6继承之super

在继承的多种方法中,最常用的最方便的还是ES6继承

一个简单的案列如下:

      //拖拽函数
        class Drag {
            constructor(selector) {
                this.box = document.querySelector(selector)
                this.bindEvents()
            }
            bindEvents(e) {
                this.box.onmousedown = (e) => {
                    let x = e.offsetX
                    let y = e.offsetY
                    document.onmousemove = (e) => {
                        let top = e.clientY - y
                        let left = e.clientX - x
                        this.move(left, top)
                    }
                    document.onmouseup = function () {
                        document.onmousemove = null
                    }

                    //阻止浏览器默认事件
                    e.preventDefault()
                }
            }
            move(left, top) {
                this.box.style.left = left + 'px'
                this.box.style.top = top + 'px'
            }
        }
        class drag extends Drag {
            constructor(selector) {
                **super(selector)**
            }
            //重写move
            move(left, top) {
                if (left < 0) left = 0
                if (top < 0) top = 0
                if (left > window.innerWidth - this.box.offsetWidth) left = window
                    .innerWidth - this.box.offsetWidth
                if (top > window.innerHeight - this.box.offsetHeight) top = window
                    .innerHeight - this.box.offsetHeight
                this.box.style.left = left + 'px'
                this.box.style.top = top + 'px'
            }
        }     

在学习这部分的时候,我个人不太理解super这个点。

  • 1.super表示父类的构造函数,并且子类的构造函数必须执行一次super
  • 2.super返回子类的实例,super内部的this指向子类的实例即:super()相当于a.prototype.constuctor.call(this)
  • 3.super指向父类的原型对象,定义在父类实例上的方法或属性无法通过super调用,但是定义在原型上的属性和方法可以获取到子类中super.aa()相当于a.prototype.aa()