Pavel Andorel
Pavel Andorel

Reputation: 23

What's the difference Object.call() and Object.__proto__.call()?

Object doesn't have it's own method call, so it takes it from proto, but why then the results are different ?

// Look at results in your browser's console

console.log(
  Object.call(null,2), // Number {2}
  Object.__proto__.call(null,2), // undefined

  Object.call(null,''), // String {""}
  Object.__proto__.call(null,'') // undefined
);

Upvotes: 2

Views: 48

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

Object.call is a reference to Function.prototype.call (because Object.__proto__ is Function.prototype):

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

Object is a constructor function (eg, new Object(...) gives you an Object). Invoking Object.call results in a call to Function.prototype.call with a calling context of Object, which Function.prototype.call uses to figure out which function needs to be called.

So

Object.call(null,2)

is basically the same thing as

Object(2);

which gives you a number inside an object wrapper.

In contrast, with Object.__proto__.call, you're calling Function.prototype.call with a calling context of Object.__proto__. But Object.__proto__ is Function.prototype. Function.prototype, per the specification:

accepts any arguments and returns undefined when invoked.

console.log(Function.prototype());

So, when .call is called with it, no matter what, it'll just return undefined (but it won't throw an error or anything, even though you might think it should - invoking Function.prototype doesn't really make any sense).

The following expressions are all doing the exact same thing:

Object.__proto__.call(null,2) // undefined
Function.prototype.call(null,2) // undefined
Function.prototype(2) // undefined

Upvotes: 3

Related Questions