Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing JavaScript statement: "var x = new this();"

I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.

Firstly, "JavaScript OOP - the smart way" at http://amix.dk/blog/viewEntry/19038

See the implementation section:

var parent = new this('no_init');

And also "Simple JavaScript Inheritance" on John Resig's great blog.

var prototype = new this();

What does new this(); actually mean?

This statement makes no sense to me because my understand has been that this points to an object and not a constructor function. I've also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.

My head has gone off into a complete spin.

Could someone please explain this in detail?

like image 765
Adam Mikulasev Avatar asked Aug 13 '10 03:08

Adam Mikulasev


1 Answers

In a javascript static function, you can call new this() like so,

var Class = function(){}; // constructor
Class.foo = function(){return this;} // will return the Class function which is also an object

Therefore,

Class.foo = function(){ return new this();} // Will invoke the global Class func as a constructor

This way you get a static factory method. The moral of the story is, not to forget functions are just like any other objects when you are not calling them.

like image 181
Abel Terefe Avatar answered Nov 13 '22 04:11

Abel Terefe