你的问题有点含糊;但我猜你是在问为什么开发人员有两种onMouseMove
方法,而不是把所有的工作合二为一,即:
var Main = {
onMouseMove: function(event) {
// Why not just have the implementation here?
// Why are we delegating it to the other method?
_onMouseMove(event)
},
_onMouseMove: function(event){
// ...length implementation...
}
}
答案是因为JavaScript 是如何处理范围的。简而言之,this
大多数经典 OOP 语言(如 Java)中的键始终是指Main
Function 范围内的父类 ( ) - JavaScript 不是这样工作的。
由于 JavaScript 中没有经典的类,因此this
关键字实际上是指调用它的函数;这就是为什么new
关键字在通过其构造函数创建新对象时如此不同的原因;例如:
function MyConstructor = function () {
// Assign a member property
this.aProperty = "An Example";
}
// Using the new keyword; a new scope is created for the call which refers to the
// object about to be created (and returned).
var withNew = new MyConstructor();
console.log(withNew.aProperty); // 'An Example'
// Without the new keyword...
var withoutNew = MyConstructor();
console.log(withoutNew.aProperty); // undefined
// Because we didn't use new, the calling function scope was applied, so
// the `this` keyword resolves caller's scope.
console.log(this.aProperty) // 'An Example'
通过委派 fromonMouseMove
到_onMouseMove
范围,仍然绑定到Main
对象,而不是绑定到触发鼠标事件的对象。另一种更易读的方法是使用委托,或者如果你使用的是 ES5,Function.bind
var Main = {
enable: function() {
window.addEventListener('mousemove', onMouseMove.bind(this), false);
},
onMouseMove: function(event) {
// ...lengthy implementation...
}
}