Question

In Javascript you can get inheritance through object prototypes or you can have encapsulation via a closure that returns an interface object to the bits you want to expose. Is there any way you can have both simultaneously? If so, what would be a good way to go about it?

Was it helpful?

Solution

Here's an example:

function Base(thing) {
    this.getThing = function() {
        return thing;
    };
}
Base.prototype.cappedThing = function() {
    return this.getThing().toUpperCase();
};

function Derived(thing) {
    Base.call(this, thing);
}
Derived.prototype = Object.create(Base.prototype);

var d = new Derived("foo");
console.log(d.cappedThing()); // "FOO", through inheritance and encapsulation

But if the question is really: Does JavaScript have anything like "protected" in various class-based languages (methods available to "subclasses" but not when you directly instantiate the base class), then the answer is no, it doesn't. You can get close if the base and derived are defined in a shared, but otherwise private, scope, and even more so when ES6's Name objects are commonplace, but nothing that spans completely independent compilation/scope units.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top