面向过程改变成面向对象三步曲

  
  
  //  面向过程改变成面向对象三步曲   //
  
  

  //第一步,用面向过程的方法完成功能
  window.onload = function () {
      var oDiv = document.getElementById("div1");
      oDiv.onmousedown = function (ev) {
          var ev = ev || window.event;
          var disX = ev.clientX - oDiv.offsetLeft;
          var disY = ev.clientY = oDiv.offsetTop;
          document.onmousemove = function (ev) {
              var ev = ev || window.event;
              oDiv.style.left = ev.clientX - disX + "px";
              oDiv.style.top = ev.clientY - disY + "px";
          };
          document.onmouseup = function () {
              document.onmousemove = document.onmouseup = null;
          };
      };
  };

  //第二步
  //  1onload里面不能存在函数包含函数,所以将所有的函数都拖出来
  //  2,将函数中需要用到的变量拖出来,作为全局变量


  var oDiv = null;
  var disX = 0;
  var disY = 0;

  window.onload = function () {
      oDiv = document.getElementById("div1");
      oDiv.onmousedown = fnDown;
  };

  function fnDown(ev) {
      var ev = ev || window.event;
      disX = ev.clientX - oDiv.offsetLeft;
      disY = ev.clientY = oDiv.offsetTop;
      document.onmousemove = fnMove;
      document.onmouseup = fnUp;
  };

  function fnMove(ev) {
      var ev = ev || window.event;
      oDiv.style.left = ev.clientX - disX + "px";
      oDiv.style.top = ev.clientY - disY + "px";
  };

  function fnUp() {
      document.onmousemove = document.onmouseup = null;
  };

// 第三步
//  1,将构造函数从onload里拖出来
//  2,将所有的全局变量变成构造函数的属性
//  3,将所有的函数都变成构造函数原型上的方法
//  4,调整this指向
//   PS:构造函数里存在 定时器 或者 事件的情况下,this指向通常容易发生变化
//       解决方法就是 先_this = this存储一下,然后在定时器或事件下面包一层函数,并在这一层函数中使用_this;         
window.onload = function () {
    new Drag("div1");
};

function Drag(id) {
    this.oDiv = document.getElementById(id);
    this.disX = 0;
    this.disY = 0;
    var _this = this;
    this.oDiv.onmousedown = function(){
        _this.fnDown();
    };
}

Drag.prototype.fnDown = function(ev) {
    var ev = ev || window.event;
    var _this = this;
    this.disX = ev.clientX - this.oDiv.offsetLeft;
    this.disY = ev.clientY - this.oDiv.offsetTop;
    document.onmousemove = function(){
        _this.fnMove();
    };
    document.onmouseup = function(){
        _this.fnUp();
    };
};

Drag.prototype.fnMove = function(ev) {
    var ev = ev || window.event;
    this.oDiv.style.left = ev.clientX - this.disX + "px";
    this.oDiv.style.top = ev.clientY - this.disY + "px";
};

Drag.prototype.fnUp = function() {
    document.onmousemove = document.onmouseup = null;
};

你可能感兴趣的:(JS,常用知识)