鍍金池/ 問答/HTML/ js oop編程中報錯,this.xxx is not a function

js oop編程中報錯,this.xxx is not a function

圖片描述

圖片描述

有人知道原因嗎....

以下源碼

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
  #div {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
  }

  </style>
</head>

<body>
  <div id="div"></div>
</body>
<script>
function fn() {
  this.div = document.getElementById('div');
  this.init();
}
fn.prototype.init = function() {
  
  this.div.addEventListener("mousedown", this.fnDown);

  
}
fn.prototype.fnMove = function(e) {
  var _this = this;
  _this.div.style.left = e.pageX - _this.dirX + 'px';
  _this.div.style.top = e.pageY - _this.dirY + 'px';
};
fn.prototype.fnUp = function() {
  document.onmousemove = document.onmouseup = null;
};
fn.prototype.fnDown=function(e) {
    var _this = this;
    _this.dirX = e.pageX - this.offsetLeft;
    _this.dirY = e.pageY - this.offsetTop;
    document.onmousemove = function(e) {
      _this.fnMove(e);
    }
    document.onmouseup = function() {
      _this.fnUp();
    }
}

var fn1 = new fn();

</script>
</html>
回答
編輯回答
紓惘

溫馨提示一下其中的一個小細節(jié)錯誤:

fn.prototype.fnDown=function(e) {
    var _this = this;
    _this.dirX = e.pageX - _this.div.offsetLeft; //直接this應(yīng)該是獲取不到的吧?
    _this.dirY = e.pageY - _this.div.offsetTop;
    document.onmousemove = function(e) {
      _this.fnMove(e);
    }
    document.onmouseup = function() {
      _this.fnUp();
    }
}
2018年2月28日 04:26
編輯回答
嫑吢丕
this.div.addEventListener("mousedown", this.fnDown);
//改為
this.fnDown();

然后把mousedown放在fnDown里

2017年6月24日 10:24
編輯回答
久礙你
this.div.addEventListener("mousedown", this.fnDown);

相當于==>

var fnDown=this.fnDown;
this.div.addEventListener("mousedown", fnDown);

fnDown變量只是引用了當前對象的fnDown對象,當這個函數(shù)對象執(zhí)行的時候

var _this = this;
_this.dirX = e.pageX - this.offsetLeft;
_this.dirY = e.pageY - this.offsetTop;
document.onmousemove = function(e) {
  _this.fnMove(e);
}
document.onmouseup = function() {
  _this.fnUp();
}

此時的this是當前執(zhí)行環(huán)境下的全局對象,這個對象就是window,而在window對象下顯然沒有fnMove函數(shù)對象的定義,所有報錯了。
可以通過bind函數(shù)綁定this對象的方式修改這個問題

this.div.addEventListener("mousedown", this.fnDown.bind(this));

var _this=this;
this.div.addEventListener("mousedown", function(){
    _this.fnDown.apply(_this,Array.prototype.slice.apply(arguments,[0]));
});
2017年9月2日 14:53