是否可以使用对某些函数的调用属性的引用并将其作为值传递?
Is it possible to use a reference to some function's call attribute and pass it around as a value?
这不起作用:
-> f = Number.prototype.toLocaleString.call
<- ƒ call() { [native code] }
-> typeof f
<- "function"
-> f(1)
<- Uncaught TypeError: f is not a function
at <anonymous>:1:1
是否可以引用和使用某些函数的 call
"method" 并将其用作常规函数?
不,call
is a method (inherited from Function.prototype.call
) and like any shared method needs to be bound 到它的目标,如果你想将它用作普通函数。在这种情况下,目标对象是 toLocaleString
函数:
const f = Function.prototype.call.bind(Number.prototype.toLocaleString);
console.log(f(1));
问题是any函数的call
属性等价于Function.prototype.call
,不能单独调用,没有调用上下文:
console.log(Number.prototype.toLocaleString.call === Function.prototype.call);
解决办法是显式给新创建的函数一个原函数的调用上下文,可以用bind
:
const f = Number.prototype.toLocaleString.call.bind(Number.prototype.toLocaleString);
console.log(f(3333));
这不起作用:
-> f = Number.prototype.toLocaleString.call
<- ƒ call() { [native code] }
-> typeof f
<- "function"
-> f(1)
<- Uncaught TypeError: f is not a function
at <anonymous>:1:1
是否可以引用和使用某些函数的 call
"method" 并将其用作常规函数?
不,call
is a method (inherited from Function.prototype.call
) and like any shared method needs to be bound 到它的目标,如果你想将它用作普通函数。在这种情况下,目标对象是 toLocaleString
函数:
const f = Function.prototype.call.bind(Number.prototype.toLocaleString);
console.log(f(1));
问题是any函数的call
属性等价于Function.prototype.call
,不能单独调用,没有调用上下文:
console.log(Number.prototype.toLocaleString.call === Function.prototype.call);
解决办法是显式给新创建的函数一个原函数的调用上下文,可以用bind
:
const f = Number.prototype.toLocaleString.call.bind(Number.prototype.toLocaleString);
console.log(f(3333));