通过-拖拽-来了解js中的this指向

2017-10-12  本文已影响0人  风之伤_3eed

虽然大概了解js中this的指向问题,但只有实践才有深刻的认识,通过对“拖拽”进行逐步对this进行分析,才深刻理解this在不同的位置的指向。
该代码使用的是面向对象的思想。

首先建立一个构造函数,在他的内部添加属性。

function Box(a){}

在构造函数中获取该物体。this.ele即为获取到的物体
为了在后续方便将对象Box("pic")保存在self中
这里的this.ele为获取到的物体
这里的this为a对象Box("pic");

 this.ele = document.getElementById(a);
        var self = this;
        // console.log(this.ele)
        //console.log(this)

给该物体添加鼠标按下事件属性
阻止浏览器默认行为
这里的this指的是this.ele
将鼠标点击的当前位置设置为物体左上角
调用对象Box的move属性,由于在此函数中this指向this.ele所以在前面保存this的self便派上用场

this.ele.onmousedown=function(e){
            e.preventDefault()
            //console.log(this)
             self.detaX = e.clientX - this.offsetLeft;
            // console.log(detaX)
             self.detaY = e.clientY - this.offsetTop;
            self.move()  
            }

给该物体绑定随鼠标运动
this为a对象Box("pic")
this为document

this.move=function(){
            //console.log(this);
                document.onmousemove=function(e2){
                    //console.log(this);
                    //console.log(self.ele)
                self.ele.style.left=(e2.clientX - self.detaX) + "PX";
                self.ele.style.top=(e2.clientY - self.detaY) + "PX";
                //console.log(e2.clientY - self.detaY)    
                }  
                document.onmouseup=function(){
                    document.onmousemove=null;
                }
        }

最后要记得调用构造函数才可以。

var a=new Box("pic");
上一篇 下一篇

猜你喜欢

热点阅读