在学习Javascript时,我尝试重新声明函数的apply属性。到目前为止没有问题。
function foo() { return 1; }
alert(foo()); // 1
alert(foo.apply(null)); // 1
foo.apply = function () { return 2; }
alert(foo()); // 1
alert(foo.apply(null)); // 2
<小时/>
现在,我尝试让 apply 执行更多操作并调用“旧”apply(如日志记录)。
var old = foo.apply;
foo.apply = function() {
alert("A");
return old(null);
}
alert(foo.apply(null));
我明白
<小时/>TypeError: Function.prototype.apply was called on [object Window], which is a object and not a function
我试过了
foo.apply = function() {
alert("A");
return arguments.callee[Function.prototype.apply](null);
}
alert(foo.apply(null));
我明白了
<小时/>TypeError: Property 'function apply() { [native code] }' of object function () { alert("A"); return arguments.calleeFunction.prototype.apply; } is not a function
有什么真正的方法可以帮助我尝试吗?或者由于 Function.prototype.apply 是 native 代码而存在一些限制?
最佳答案
是的。 apply
期望应用于函数(是的,正是它本身),而您使用它的方式(通过 old()
)使其 this
value全局对象(窗口
)。所以你可以这样做:
var old = foo.apply; // === Function.prototype.apply
foo.apply = function() {
// "this" is the function foo
alert("A");
return old.apply(this, arguments); // applying the (old) apply function on foo
// or better without any arguments:
return old.call(this); // like this(); which is foo()
}
alert(foo.apply(null));
// and the call solution with an argument:
foo.apply = function(context) {
return old.call(this, context);
// like this.call(context);
// which is foo.call(context)
// which is like context.foo()
}
关于javascript - 在 apply 的重新声明中调用 Function.prototype.apply (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069906/