質問は少し曖昧です。onMouseMove
しかし、開発者がすべての作業を1つで行うのではなく、2つの方法を使用する理由を尋ねていると思います。つまり、次のようになります。
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
関数のスコープ内の親クラス()を参照します-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'
から委任することによりonMouseMove
、_onMouseMove
スコープはMain
、マウスイベントをトリガーしたオブジェクトにバインドされるのではなく、オブジェクトにバインドされたままになります。これを実現するもう1つのより読みやすい方法は、デリゲートを使用することです。ES5を使用している場合は、Function.bindを使用します。
var Main = {
enable: function() {
window.addEventListener('mousemove', onMouseMove.bind(this), false);
},
onMouseMove: function(event) {
// ...lengthy implementation...
}
}