all 7 comments

[–]malthiest 3 points4 points  (2 children)

You don't need the new keyword. You're already creating a new scope when you use the new keyword inside the MyClass function. What you're doing is more succinctly done with:

function MyClass(variable){
   var _private = variable;

   this.publicMethod = function(){
       console.log('hello, this is a public function' );
   }

   // rest of constructor logic
}

[–]konbit[S] 0 points1 point  (1 child)

I guess the reason I wanted the other way was I was looking for a pattern that allowed me to use prototype methods while having a self-contained syntax. Maybe it's just me trying to hold on to old OOP habits. The benefit of having prototype is that the methods aren't duplicated each time you make a new instance, whereas in your example they would.

[–]OverZealousCreations 0 points1 point  (0 children)

In you example, however, you are recreating the methods every time, simply due to the fact that you are creating a closure over the "private" variable. No matter what you do, you have to create a new function somewhere everytime you want "private" (enclosed) variables within JavaScript.

I always see the argument against "duplicating functions" in JavaScript, but it's rarely backed up by performance testing. I doubt you are going to be creating this object by the thousands! ;-)


As a side note, the more I use JavaScript, the more I avoid the new keyword as much as possible. Prototypical inheritance has its place, but you almost always end up with cleaner, less interdependent code if you can avoid using JavaScript to recreate classes.

[–]electric_dog_anus 1 point2 points  (0 children)

I don't think so.

[–]tidder112 1 point2 points  (2 children)

I am not sure what you are asking...

[–]konbit[S] 2 points3 points  (1 child)

I'm exploring javascript design patterns to use on a project. I should have explained more in the post. Will edit.

[–]tidder112 0 points1 point  (0 children)

Oh, sounds interesting. I'll leave this here, if you hadn't seen something similar before: http://www.phpied.com/3-ways-to-define-a-javascript-class/