16-1 ECMA5与ECMA6的函数定义

时间:2022-11-24 06:58:50
ECMA5:

function Drag(id){
this.ele = document.getElementById(id);
var that = this;
this.ele.onmousedown = function(evt){
that.fnDown(evt);
}
this.fnDown = function(evt){
var e = evt || window.event;
this.disX = e.offsetX;
this.disY = e.offsetY;
var that = this;
document.onmousemove = function(evt){
that.fnMove(evt);
}
document.onmouseup = this.fnUp;
}
this.fnMove = function(evt){
var e = evt || window.event;
this.ele.style.left = e.pageX - this.disX + 'px';
this.ele.style.top = e.pageY - this.disY + 'px';
}
this.fnUp = function(){
document.onmousemove = null;
}
} ECMA6: class Drag{
constructor(id){
//属性
this.ele = document.getElementById(id);
var that = this;
this.ele.onmousedown = function(evt){
that.fnDown(evt);
}
}
fnDown(evt){
var e = evt || window.event;
this.disX = e.offsetX;
this.disY = e.offsetY;
var that = this;
document.onmousemove = function(evt){
that.fnMove(evt);
}
document.onmouseup = this.fnUp;
}
fnMove(evt){
var e = evt || window.event;
this.ele.style.left = e.pageX - this.disX + 'px';
this.ele.style.top = e.pageY - this.disY + 'px';
}
fnUp(){
document.onmousemove = null;
}
}