0

Any JavaScript object inherits its properties from Object (unless you do something like Object.create(null)). So why is the following not possible?

a={x:1,y:2}
    Object {x: 1, y: 2}
Object.prototype.isPrototypeOf(a)
    true
a.toString()
   "[object Object]"//YES, BECAUSE a INHERITS OBJECT toString() PROPERTY
a.keys()
   TypeError: undefined is not a function// BUT WHY NOT keys()
Object.keys(a)
   ["x", "y"]// WHILE THE OBJECT HAS keys() METHOD FROM ECMA5 SPECIFICATION

Based on my understanding then, the only reason it had not worked should be because keys() method is un-inheritable but I have never seen how to make some properties un-inheritable in JavaScript.

Am I missing something about how prototypical chain works?

1 Answer 1

2

a.toString is inherited from Object.prototype.toString, not Object.toString. Object.keys is not on Object.prototype.

You could add it:

Object.prototype.keys = function keys() {
    return Object.keys(this);
};

(Don’t, of course.)

Sign up to request clarification or add additional context in comments.

1 Comment

Such a nice answer and short! Thanks for clearing the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.