Question

All newly created objects (with the exception of objects created using Object.create(null)) contain the object Object.prototype in their prototype chain. These newly created objects can call newObject.toString() because toString is defined on Object.prototype.

However, the internal prototype of Object is said to be null. If that's the case, why the heck can I do this:

Object.toString();
// prints: "function Object() { [native code] }"

Perhaps I've answered my own question. Is toString also defined on the Object constructor function?

Why?!

Was it helpful?

Solution

> var obj = Object.create(null);
  undefined
> obj.toString();
  TypeError: undefined is not a function
> Object.toString();
  "function Object() { [native code] }"

See, obj is created with null as the prototype, so when you call .toString() on it, error will happen.

But Object self is a function, and whose prototype is a Function object, which has the .toString() method.

OTHER TIPS

Functions don't have to exist in an object's prototype to be invokable on an object.

Given a simple example...

x = {}
x.y = function () { }

y is not in x's prototype, yet I can use x.y().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top