Doubt about a particular pattern of Javascript class definition
Posted
by fenderplayer
on Stack Overflow
See other posts from Stack Overflow
or by fenderplayer
Published on 2010-05-25T21:32:53Z
Indexed on
2010/05/25
21:51 UTC
Read the original article
Hit count: 153
Recently i saw the following code that creates a class in javascript:
var Model.Foo = function(){
// private stuff
var a, b;
// public properties
this.attr1 = '';
this.attr2 = '';
if(Model.Foo._init === 'undefined'){
Model.Foo.prototype = {
func1 : function(){ //...},
func2 : function(){ //... },
//other prototype functions
}
}
Model.Foo._init = true;
}
// Instantiate and use the class as follows:
var foo = new Model.Foo(); foo.func1();
I guess the _init variable is used to make sure we don't define the prototypes again. Also, i feel the code is more readable since i am placing everything in a function block (so in oop-speak, all attributes and methods are in one place). Do you see any issues with the code above? Any pitfalls of using this pattern if i need to create lots of classes in a big project?
© Stack Overflow or respective owner