linstantnoodles
linstantnoodles

Reputation: 4400

If the prototype of `Object` in JavaScript is null, why can I do Object.toString()?

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?!

Upvotes: 0

Views: 120

Answers (2)

xdazz
xdazz

Reputation: 160853

> 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.

Upvotes: 2

user229044
user229044

Reputation: 239301

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().

Upvotes: 0

Related Questions