1
votes

When I switched to the revealing module pattern in Javascript, it was a sigh of relief. No more this, that, exports.func, that.func.bind(that), function() { that.success(); }, etc. In fact, in my modules no more occurrences of 'this' even exist, hence less confusion and more clarity! If only I could also apply the same concept to a class. This would allow me to work within the private scope of the class, and reveal only public functions at the bottom. Here is my attempt to do this, is it even a class? Do you see any problems with this implementation?

var TestClass = function(_a) {
    var a = _a;

    function func() { console.log(a); }

    return {
        func: func
    }
};

var tc1 = new TestClass(1);
var tc2 = new TestClass(2);

tc1.func();     //1
tc2.func();     //2

EDIT: I call it the 'Revealing Class Pattern' (w3core below gave me this idea)

var TestClass = function(_a) {
    var a = _a;

    function func() {
        console.log(a);
    }

    this.func = func;
};

TestClass.prototype.shared = function() {
    console.log(5);
};

var tc1 = new TestClass(1);
var tc2 = new TestClass(2);

tc1.func();     //1
tc2.func();     //2

tc1.shared();   //5
tc2.shared();   //5

tc1.constructor;           //function TestClass()
tc1 instanceof TestClass;  //true

This method seems to fix the 'instanceof' problem as mentioned in the comments. Also, the constructor is now set to the function as well.

1
Do you see any problems with this implementation - func has to be created everytime the constructor is called. - thefourtheye
Right, I have no problem with func being recreated. For specific cases where performance will matter I would use the prototype method, but I personally think it's more important to have a clear, easy to read, and easy to understand class that works under all circumstances. - wayofthefuture
How do you Inherit from this (an important tenant of object oriented design)? - jfriend00
Then, why are you asking a question about implementing Javascript classes? Your question is now in a weird state where you ask how appropriate this is for classes, but when we point out something it can't do that is central to object oriented design, you say that doesn't matter to you. I guess we don't know what you're really asking. It sounds like you just want to defend your design rather than actually understand the potential disadvantages. IMO, you won't get very far in writing really good Javascript code if you never inherit anything. - jfriend00
Yes, that Crockford scheme does allow inheritance. FYI, he has several new schemes out too as that document is pretty old. - jfriend00

1 Answers

0
votes

Take a look at that:

function ClassName (that) {
    var that = that || this;

    function methodName1 () {

    }

    function methodName2 () { 

    }

    that.methodName1 = methodName1;
    that.methodName2 = methodName2;
}

var case1 = new ClassName();
var case2 = new ClassName({ key: "value" });
var case3 = new ClassName(case2);