How to access properties from the prototype chain that are shadowed by own properties?

Let's create an object which inherits from another anonymous object:

var obj = Object.create({
    func: function () { alert('Inherited method'); }
});

Now obj inherits the func method from that anonymous object (obj's prototype link points to that anonymous object).

obj.func(); // alerts 'Inherited method'

But if we assign a func property on obj itself, the inherited func property will be shadowed:

obj.func = function () { alert('Own method'); };

obj.func(); // alerts 'Own method'

Live demo: http://jsfiddle.net/PLxHB/

Now, if we wanted to invoke that shadowed func method (the one that alerts 'Inherited method'), what would be a good way to do that?

I've already come up one solution - see here - but it's kind-of a hack.

Answers:

Answer
Object.getPrototypeOf(obj).func();

will make sure the inherited function gets executed.

In older browsers (the above is ES5), you can use

obj.__proto__.func();

but this is deprecated.

http://jsfiddle.net/pimvdb/PLxHB/5/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.