Domanda

Hi I was wondering if there was a "cleverer" way of retrieving the top level (or any number of levels from the top) prototype in the javascript prototype chain.

The problem is that given:

  var a = Object.create(Object.prototype, {'class' : {value : 'a'}});
  var b = Object.create(a, {'class' : {value : 'b'}});
  var c = Object.create(b, {'class' : {value : 'c'}});

Can I get to a from c without writing a loop?

  var topClass = c;
  while (Object.getPrototypeOf(topClass) !== Object.prototype) {
     topClass = Object.getPrototypeOf(topClass);
  } 
  console.log('expect this to be true: '+ a === topClass);
È stato utile?

Soluzione

Can I get to a from c without writing a loop?

No, you have to do what you've done, walk your way down to the bottom (or up to the top, whichever term you prefer).

It's probably also worth pointing out that if you're going to be doing this in a browser context, your loop won't work reliably if the code you've quoted is working with an object created in another window, because the Object.prototype of one window is not === the Object.prototype of another window. But that's only important A) If you're doing this in a browser, and B) If you may be doing it on an object from another window. (If it's important for you, you can loop until you get back null and then assume that two levels prior was the first non-Object prototype in the chain...)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top