0

For the following code, I wonder why Object.getPrototypeOf(person) works, but person.getPrototypeOf(person) won't work? I thought the rule is: if the object doesn't have such property or method, it will go up the prototype chain to try and get it, and call it on this (such as Animal.getName.call(this) where this is the context of the woofie object). So in that case, person.getPrototypeOf(person) should become Object.getPrototypeOf.call(person, person) and should work too?

function Person(name) {
    this.name = name;
}

var person = new Person("Ang Lee")

console.log("the prototype of person is", Object.getPrototypeOf(person));

Update: for the answers that say getPrototypeOf is a static method, does that mean:

function Person(name) {
    this.name = name;
    this.foo = function() { ... }
}

Person.bar = function() { ... }

that foo is "in the chain", and callable by any inherited objects, while bar is not, and bar is like getPrototypeOf, which is a static method?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

3 Answers3

2

Object.getPrototypeOf is a property of the Object type itself, and not of the prototype of Object.

Because it's not actually in the prototype chain, it won't be found when you call person.getProtoTypeOf().

It's more akin to a "static method" as seen in other OO languages.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • do you think what is in the update of the question is correct? (is this the only way a static method is defined?) – nonopolarity Sep 30 '12 at 14:16
  • Yes, what you've described in your update is more or less correct. `Person.bar` is a static method, and `.foo` is an instance method. However the way you've written it `foo` is **not** on the prototype chain, because it is only bound to each instance at creation time, rather than added to `Person.prototype`. – Alnitak Sep 30 '12 at 14:40
1

.getPrototypeOf is a function put on Object, not on it's prototype. You can look it up if you want:

"getPrototypeOf" in Object.prototype; // false
David G
  • 94,763
  • 41
  • 167
  • 253
1

If getPrototypeOf were a method contained in Object.prototype, it would also be available on objects of type Person, however, getPrototypeOf is attached to Object, which is only the constructor function of Object instances, not the prototype.

For some reason, the creators of Javascript decided that prototypes are attached to constructor functions and not vice versa; if they hadn't made such questionable decision, you would not have had to ask this question.

P.S. anybody interested in a more elegant/clean implementation of prototype based object inheritance can check out http://iolanguage.com/

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111