Modern Javascript Development: constructors and objects
JavaScript doesn't have a "class" keyword or any formal class construct. Instead, functions are 1st class objects. When you write a function, you are essentially writing a constructor for a new object.
Here we are defining a object constructor called "newClass" and assigning some member values.
-
function newClass() {
-
this.name = "newClass";
-
this.options = {size:42};
-
};
-
-
var myInstance = new newClass();
-
alert(myInstance.name);
-
alert(myInstance.options.size);
You can also specify arguments for the constructor just like any other function and assign the argument values to the objects members.
-
function newClassInitialzed(name, options) {
-
this.name = name;
-
this.options = options;
-
};
-
var anotherInstance = new newClassInitialzed("John", {size:42})
-
alert(anotherInstance.name);
-
alert(anotherInstance.options.size);
So what happens if you don't want to pass the name and options to the constructor every time? You can specify defaults for the member variables values using the logical OR ( || ) operator in JavaScript. The logical OR operator has a short-circuit which always returns "true" if the first argument is true.
-
function defaultArgValues(name, options){
-
this.name = name || "unknown";
-
this.options = options || {size:42};
-
};
-
var defaultArgsInstance = new defaultArgValues();
-
alert(defaultArgsInstance.name);
-
alert(defaultArgsInstance.options.size);
Since functions are first class objects, we can pass them as arguments in our constructors as well.



Pingback: Jason Haley