以下代码调用console.log打印"hello":
console.log.call(console, "hello")
Run Code Online (Sandbox Code Playgroud)
但是,下面的代码抛出TypeError:
x = console.log.call
x(console, "hello")
Run Code Online (Sandbox Code Playgroud)
抛出:
Uncaught TypeError: x is not a function
at <anonymous>:1:1
Run Code Online (Sandbox Code Playgroud)
谁能解释这个奇怪的场景?
(当然,这是相同的两个call和apply)
.call获取从其this参数调用的函数.
你通过x没有this参数调用它,所以它没有调用函数(或者更确切地说,它试图调用window)并给出错误.
您需要将x变量绑定到log函数:
x = console.log.call.bind(console.log);
Run Code Online (Sandbox Code Playgroud)
奖金:.call来自Function.prototype,无论你如何访问它都是一样的.因此,Function.call.bind(console.log)也有效(因为Function是一个功能,因此有.call).同样如此Date.call.
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |