Question

Why does the marked line fail to find protectedACMember?

var Module = (function (ns) {

    function AbstractClass() {
        this.protectedACMember = "abstract";

        this.abstractPublicACMethod = function (input) {
            this.methodToImplement();                   
        }
    }

    ConcreteClass.prototype = new AbstractClass();
    function ConcreteClass(){
        var privateCCMember = "private CC";

        var privateCCMethod = function(){
            alert(this.protectedACMember); // cant find protectedACMember
        }

        this.methodToImplement = function(){ 
            privateCCMethod();
            console.log('Implemented method '); 
        }

    }

    ns.ConcreteClass = ConcreteClass;   

    return ns;

})(Module || {});

//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();

are there any good patterns for simulating private, protected and public members? Static/non-static as well?

Was it helpful?

Solution

You should change that part of code like this:

    var self = this;
    var privateCCMethod = function(){
        alert(self.protectedACMember); // this -> self
    }

This way you get the reference in the closure.

The reason is, that "this" is a reserved word, and its value is set by the interpreter. Your privateCCMethod is an anonymous function, not the object property, so if you call it simply by privateCCMethod() syntax, this will be null. If you'd like "this" to be bound to something specific you can always use .call syntax, like this:

privateCCMethod.call(this)

OTHER TIPS

Another way to ensure that this means what you want is to use bind. Bind allows you to ensure a function is called with a specific value of this.

Most newer browsers support it (even IE9!) and there's a workaround for those that don't.

Bind - MDN Documentation

It fails to find protectedACMember because what the this keyword means changes when you enter the function privateCCMethod. A common practice is to store the outer this for use inside the functions:

function ConcreteClass(){
    var privateCCMember = "private CC";

    // store the outer this
    var that = this;
    var privateCCMethod = function(){
        alert(that.protectedACMember);
    }
    ...

The rest of your questions are fairly loaded and should probably be posted as a separate question.

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