美文网首页
[JS基础]面向对象入门

[JS基础]面向对象入门

作者: Re_Vive | 来源:发表于2018-07-01 23:02 被阅读0次

    重新学习js,当然先从面向对象开始

    1、简单实现一个拖拽功能

    <style>
        #a{
            height: 200px;
            width: 200px;
            background: red;
            position: absolute;
        }
    </style>
    <body>
        <div id="a"></div>
    </body>
    

    html就是一个简单的div

    window.onload = function(){
        var d1 = new Drag('a')
        d1.init()
    }
    
    function Drag(uid){//构建一个函数,为函数添加属性
        this.oDiv = document.getElementById(uid)
        this.disX = 0
        this.disY = 0
    }
    
    Drag.prototype.init = function(){//初始化方法
        let that = this
        this.oDiv.onmousedown = function(){
            that.fnDown()
        }
    }
    
    Drag.prototype.fnDown = function(){
        let that = this  //将指向object的this保存进that
        var e = e || window.event
        this.disX = e.clientX - this.oDiv.offsetLeft
        this.disY = e.clientY - this.oDiv.offsetTop
        document.onmousemove = function(){
            //console.log(this)    这里会指向这个dom节点而不是object
            that.fnMove()
        }
        document.onmouseup = this.fnUp
    }
    
    Drag.prototype.fnMove = function(){
        var e = e || window.event
        this.oDiv.style.left = e.clientX - this.disX + 'px'
        this.oDiv.style.top = e.clientY - this.disY + 'px'
    }
    
    Drag.prototype.fnUp = function(){
        document.onmousemove = null
        document.onmouseup = null
    }
    

    面向对象的主要难点就是这this指向的问题,虽然都叫this,但在不同的地方this会不同,咱需要将this都指向object

    相关文章

      网友评论

          本文标题:[JS基础]面向对象入门

          本文链接:https://www.haomeiwen.com/subject/rzqhuftx.html