简体   繁体   English

为什么我们在JavaScript中有Function.call?

[英]Why do we have Function.call in javascript?

> Function.call == Function.prototype.call
true
> Function.prototype == Function
false

Why do Function.prototype.* methods exist as Function.* ? 为什么Function.prototype.*方法作为Function.*存在Function.* It seems inconsistent. 这似乎不一致。

This isn't the case with any other primary type ( Array.slice doesn't exist but Array.prototype.slice does). 任何其他主要类型都不是这种情况( Array.slice不存在但Array.prototype.slice不存在)。

Because Function itself is the prototype of Function 由于Function本身的原型Function

console.log(Function instanceof Function);
console.log(Object.getPrototypeOf(Function) === Function.prototype);

So, all the functions in the Function s prototype are available in Function also. 因此, Function原型中的所有Function也可以在Function

Quoting the specification , 引用规范

The Function prototype object is itself a Function object (its [[Class]] is "Function") Function原型对象本身就是一个Function对象(它的[[Class]]是“Function”)


Another way to confirm this would be, 确认这一点的另一种方法是,

console.log(Function.call === Function.prototype.call);

it means that the Function.call object and Function.prototype.call object are the same. 这意味着Function.call对象和Function.prototype.call对象是相同的。

console.log(Function.hasOwnProperty('call'));

it means that the Function object itself doesn't have call property. 这意味着Function对象本身没有call属性。

console.log(Function.prototype.hasOwnProperty('call'));

it means that Function.prototype object has the call property. 这意味着Function.prototype对象具有call属性。


Array.slice doesn't exist but Array.prototype.slice do Array.slice不存在但Array.prototype.slice可以

Because Array function's prototype is Function object, not the Array object. 因为Array函数的原型是Function对象,而不是Array对象。

console.log(Object.getPrototypeOf(Array) === Function.prototype);

That is why we get call , apply , bind etc on the Array function. 这就是我们在Array函数上callapplybind等的原因。 It Array object had been the prototype of Array , then slice would have been available on the Array object also. Array对象已经原型Array ,然后slice将有上是可利用Array对象也。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM