javascript : make a new safe class constructor

Posted by guilin ?? on Stack Overflow See other posts from Stack Overflow or by guilin ??
Published on 2010-12-25T16:58:23Z Indexed on 2010/12/25 17:54 UTC
Read the original article Hit count: 143

Filed under:
|
|

sometimes we loss the new keyword when define new object,

obj = new Clazz(); //correct
obj = Clazz(); //wrong, but no syntax error, hard to debug.

I want to write a function to help me create Class and make it new safe.

var Class = function(constructor){
   //when constructor
   // if not call by new
     return new constructor();
   // else
     constructor();

}

var MyClazz = Class(function(name){
    this.name = name
}, SuperClazz1, SuperClass2 )

MyClazz.extend({
    show: function(){console.log(this.name)}
})

obj1 = new MyClazz(); 
obj2 = MyClazz();
// obj1 should same as obj2

Is it possible, any exists module?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about oop