不能直接使用Function.prototype.call [英] Can't use Function.prototype.call directly

查看:45
本文介绍了不能直接使用Function.prototype.call的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function f(a) { return a}

f(1) // => 1

f.call(null, 1) // => 1

Function.prototype.call(f, null, 1) // => undefined

为什么最后一行返回 undefined ,我以为他们是一样的。

Why the last line return undefined, I thought they are the same.

推荐答案

这些将是相同的:

function f(a) { return a}

console.log(f(1)); // => 1

console.log(f.call(null, 1)); // => 1

console.log(Function.prototype.call.call(f, null, 1)); // => 1

这里有一个解释:

根据 spec Function.prototype.call 返回抽象操作调用(func,thisArg,argList)

因此, f.call(null,1)将返回抽象操作调用(f,null,1)其中 f 是被调用的函数, null 是来自的上下文它被称为, 1 是传递给 f 的参数。这将为您提供所需的输出。

Therefore, f.call(null, 1) will return the abstract operation Call(f, null, 1) where f is the function being called, null is the context from which it is called, and 1 is the argument passed to f. This will give you the desired output.

基于此, Function.prototype.call(f,null,1)将导致抽象操作调用(Function.prototype,f,null,1)其中 Function.prototype 是被调用的函数, f 是上下文, null 1 是传递给 Function.prototype 的参数。当然这不会按预期工作。

Based on that, Function.prototype.call(f, null, 1) will result in the abstract operation call(Function.prototype, f, null, 1) where Function.prototype is the function being called, f is the context, and null and 1 are the arguments passed to Function.prototype. Of course this will not work as intended.

然而, Function.prototype.call.call(f,null,1)将返回抽象调用操作 Call(Function.prototype.call,f,null,1),其中 Function.prototype.call 是要调用的函数, f 是调用它的上下文 null 1 作为参数传递。

However, Function.prototype.call.call(f, null, 1) will return the abstract call operation Call(Function.prototype.call, f, null, 1), where Function.prototype.call is the function to be called, f is the context from which it is called, and null and 1 are passed as arguments.

那么它会是什么样的?

好吧,因为 f 是上下文而调用是用(null,1)调用的函数,最终结果与: f.call(null,1)

Well, since f is the context and call is the function being invoked with (null,1), the end result is identical to: f.call(null, 1).

这篇关于不能直接使用Function.prototype.call的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆