RSS Feed

Classical constructor function in JavaScript class

January 29, 2011 by Dusan Gledovic

I was in search (~5 min) for classical constructor for classes in JavaScript. What I found is nothing. It lasted too short, I guess, but anyway I did some tests and I got to the solution that could easily act as JavaScript class constructor.

The complete Test class:

function Test(name){

	var that = this;

	var fname;

	var __construct = function(passedName){
		fname = passedName;
	}(name);

	this.getName = function(){
		return fname;
	};

	this.changeText = function(){
		document.getElementById("name").innerHTML = this.getName();
	}
}

var Test = new Test("Dusan");
Test.changeText();

And html:

<html>
	<head>
	</head>
	<body>
		<div id="name"></div>
	</body>
</html>

Output is of course: Dusan

Whole point is within few lines of code:

var __construct = function(passedName){
	fname = passedName;
}(name);

__construct is private self invoking function and it is passed name param during Test object construct. It sets fname var to name param value.

It could easily be something more complex like config object:

function Test(configObject){
	var __construct = function(params){
		fname = params["fname"];
		lname= params["lname"];
	}(configObject);

This is anything, but a complex, but you got an idea.

Notes:

  • You can name __construct function as you wish. I named it like this for clarity and because of my PHP roots. :)
  • __construct returns void so there is no possibility of revoking it. It becomes typeof “undefined”.
  • It has to be defined like var chooseContructorName = function(){…} to stay private and to parse as self invoking.

Enjoy.


No Comments »

No comments yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>