Define Private field Members and Inheritance in JAVASCRIPT module pattern

No. Privateness in JavaScript can only be done by scoping (and exporting from them: closures).

Those functions that need to access the private variables (and functions), called privileged methods need to be defined inside the constructor. Those methods that don’t (which only interact with public properties or other methods) should be defined on the prototype object, so you will get a mixed approach in the end. Potentially combined with the static values you just discovered.

Btw, not the function [code] itself is copied and memorized multiple times. Only different scope objects (lexical environments) need to be stored.

Inheritance is usually not done by creating parent objects and extending them, but by creating child instances and extending them like a parent. This is can be done by applying the parent’s constructor on the newly created child:

function ChildClass() {
    ParentClass.call(this, /* … arguments */);

    // usual body, using "this"
}

Also, the prototype of the Child inherits directly from the Parent’s prototype object. This can be done via Object.create (needs to be shimmed for legacy browsers):

ChildClass.prototype = Object.create(ParentClass.prototype, {
    constructor: {value:ChildClass}
});

Leave a Comment