1

I am already familiar with the module pattern where we define a module with private state with the funcitons closure and an exposed set of public methods. However this seems to be closer to a singleton than an object.

However what if i wanted a more object orientated pattern can I use the same structure as the module pattern but don't immediately execute, Something like this:

function MyPseudoClass(constructorArg0, constructorArg1... ) {

    var privateVar = "private!!";
    var privateComplexVar = constructorArg0;
    var privateComplexVar1 = constructorArg1;

    return {
        publicVar: "public Varaible!",
        publicMethod: function() {
            //code
            return privateVar + 1;
    }
};

Now in my code i can create instances of my pseudo class like so:

var instance = MyPseudoClass({p : 2, q : 100},"x")
var anotherInstance = MyPseudoClass({p : 3, q : 230},"y")

As far as i can tell this seems to do what i want but i haven't seen anyone using this online, are there any downsides to this approach that i should be aware of?

2
  • You're not using prototypical inheritance (you don't need to), but everything is fine. You might call this a "factory function" more than a "constructor", and you might name it getPseudoInstance. Commented Nov 25, 2013 at 16:05
  • Why are you incrementing a private string in publicMethod. Also variable is mis-spelt in publicVar Commented Nov 25, 2013 at 16:05

1 Answer 1

1

You aren't using prototypical inheritance; that is the main difference. Your main drawbacks are:

  • You cannot use instanceof to ensure that a variable is of some type (so you cannot do myVar instanceof MyPseudoClass. You don't create an instance with this method; you just create an object.
  • A prototype-based approach might be faster as there is overhead associated with closures. Furthermore, in a prototyped approach, each instance will share can share the same instance of a function (that is assigned to the prototype). But in the closure approach, each "instance" will have its own copy of the function. However, the difference is small (especially in newer browsers).

If you aren't concerned about these drawbacks, you should be ok.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.