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

标签 javascript function-prototypes native-methods

在学习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/

相关文章:

c - 为什么要使用函数原型(prototype)?

java - 在 4.0.3 之前的 Android 下运行时 native 库中的段错误

c# - MarshalAs 属性案例研究

c - C 函数原型(prototype)返回二维数组

javascript - 多重继承问题

javascript - 根据 querySelector 检查元素? (使用 native 方法,而不是 JQuery)

javascript - Async React.Component 对我不起作用

javascript - SpreadJS ClipboardPasteOptions 设置为 "All"但未应用格式

javascript - 如何抛出异常?

javascript - Material-ui V3 在获取数据(或页面加载)后不会加载第一个选项卡