gpt4 book ai didi

javascript - 如何使用 apply 重写调用?

转载 作者:行者123 更新时间:2023-12-04 02:09:37 25 4
gpt4 key购买 nike

这是问题陈述:

Imagine JavaScript didn't natively include the call function. The apply function however still exists.

Using apply, write call.

Note: console.log internally uses the 'call' function, which therefore means you can't debug using console.log as it will either call an empty function or cause an infinite loop.

这是我的尝试(无效):

Function.prototype.call = function(a) {
var args = Array.prototype.slice.apply(arguments,[1]);
Function.prototype.apply(a, args);
}

第二次尝试:

Function.prototype.call = function(a) {
var args = Array.prototype.slice.apply(arguments,[1]);
this.apply(a, args);
console.log("OKAY!");
}

var person1 = {name: 'Marvin', age: 42, size: '2xM'};
var person2 = {name: 'Zaphod', age: 42000000000, size: '1xS'};

var sayHello = function(){
alert('Hello, ' + this.name);
};

var sayGoodbye = function(){
alert('Goodbye, ' + this.name);
};

sayGoodbye.call(person2);

这似乎是在 JSFiddle 中检查出来的,但不是在我正在解决问题的平台上 (codewars.com)

编辑:谢谢。我在不使用 return 的情况下尝试了同样的方法,但代码没有通过。但是,行为似乎是一样的。回不回有什么区别?我认为我的尝试是正确的,因为 call 应该调用正在访问 call 的函数,对吗?在那种情况下,返回调用函数的结果对我来说似乎有点奇怪。

但这里是我试图推理出来的:如果我将默认调用与 foo.call(a) 一起使用,我将使用 a 调用 foo,所有返回行为都与 foo 相同。在我的第二次尝试中,我们调用了 this.apply,以便我们可以使用调用函数。 Function.prototype.apply 在我最初的尝试中不知道是谁调用了 apply。但是如果我们只是调用 apply 而没有返回,那么如果原始函数 (this) 有返回值,我们将无法取回它并且行为将与默认调用的行为不同。这样对吗?

最佳答案

Function.prototype.call = function() {
var args = Array.prototype.slice.apply(arguments,[1]);
return this.apply(arguments[0], args);
};

这是您要找的吗?

关于javascript - 如何使用 apply 重写调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21353013/

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