Why can't I .call() Function.call?

孤者浪人 提交于 2019-12-19 09:39:31

问题


In Javascript, Function.call() can call Function given a this value and zero or more arguments.

Function.call itself is a function. So in theory, Function.call should be the same (or similarly acting) function as Function.call.call.

In V8, this seems to be the case:

> Function.call === Function.call.call
true

When we call Function.call(), we get an anonymous function

> Function.call()
[Function: anonymous]

However, I can't call .call() on Function.call.

> Function.call.call()
TypeError: undefined is not a function
at repl:1:21
at REPLServer.defaultEval (repl.js:132:27)
at bound (domain.js:291:14)
at REPLServer.runBound [as eval] (domain.js:304:12)
at REPLServer.<anonymous> (repl.js:279:12)
at REPLServer.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:214:10)
at REPLServer.Interface._line (readline.js:553:8)
at REPLServer.Interface._ttyWrite (readline.js:830:14)
at ReadStream.onkeypress (readline.js:109:10)

What is going on here? Function.call is clearly a function - it's not undefined as this error message suggests.


回答1:


Short answer: The error message is very misleading. It is the same error message you get when you do

(undefined)();

Longer answer:

The second .call() is being invoked with a this of Function.call.

Calling it with no parameters causes it to call this with undefined as the this value.

Therefore, you're really doing

Function.call.call(undefined)

which means you're (metaphorically) doing

undefined.call()

which is really just

undefined()

Passing nothing (or undefined) to the this parameter of Function.call.call() is essentially negating the this context of the first Function.call() (which would be just Function itself), causing .call() to be invoked on undefined.

This yields the error message that is produced: undefined is not a function.



来源:https://stackoverflow.com/questions/40884839/why-cant-i-call-function-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!