刚开始从《权威指南》一书中学习JavaScript,有一行我无法弄清楚。以下是完整的代码:
// Replace the method named m of the object o with a version that logs
// messages before and after invoking the original method.
function trace(o, m) {
var original = o[m]; // Remember original method in the closure.
o[m] = function() { // Now define the new method.
console.log(new Date(), "Entering:", m); // Log message.
var result = original.apply(this, arguments); // Invoke original.
console.log(new Date(), "Exiting:", m); // Log message.
return result; // Return result.
};
}
作者没有对该行发表评论,我对这段代码有几个问题。
- 这分别指的是什么?此调用究竟是如何工作的?
也欢迎对此特定代码中的闭包进行解释!谢谢
>apply
调用o[m]
引用的函数,使用this
作为"上下文",并将传递给替换函数的arguments
转发到原始函数上。
上下文"是指函数的"this"绑定。如果你说var result = original.apply(null, arguments);
那么"context"将被设置为null
,并且在原始函数中对"this"的任何调用都将(或多或少)被替换为"null"。
在这种情况下,在m
中调用this
可能应该引用o
,因为它是包含对象。
Javascript在调用函数时绑定特殊的this
和arguments
变量:this
引用函数的调用者,arguments
将所有传递的参数存储在类似数组的对象中。行original.apply(this, arguments)
调用与行所在的函数相同的this
绑定和相同的参数original
,顺序相同(此处为存储在 o[m]
的匿名函数)。