gpt4 book ai didi

javascript - 在 apply 的重新声明中调用 Function.prototype.apply (Javascript)

转载 作者:行者123 更新时间:2023-11-28 20:37:39 28 4
gpt4 key购买 nike

在学习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()
}

另请查看 call 的文档和 apply “方法”(尽管我们使用 old 不是作为方法,而是作为纯函数)。

关于javascript - 在 apply 的重新声明中调用 Function.prototype.apply (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069906/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com