The diary of a .NET Developer, working on an unlaunched startup project. Also, I live and work in Southern Oregon.

Tuesday, January 27, 2009

Javascript Class Definitions

Two ways to define a class in javascript.  

At first glance, I didn’t realize what was going on in the second example, but the code is just using JSON syntax to define the prototype.

The benefit of reading other people’s code is you always learn something new.

(I picked this up browsing through the jQuery source code.)

I placed the actual source code here so you can can see it in action.

This is the way I always defined classes:

    function Person2(name, age) {
this.name = name;
this.age = age;
}

Person2.prototype.HaveBirthday = function() {
this.age++;
}

Person2.prototype.GreetWorld = function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + "years old";
}

A shorthand way using JSON syntax:

    Person.prototype = {
HaveBirthday: function() {
this.age++;
},

GreetWorld: function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + "years old";
}
};

This makes a lot more sense when you realize you can even do this:

var ben3 = { 
age: 29,
name: "Ben",
GreetWorld: function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + " years old"; },
HaveBirthday: function() { this.age++; }
};
 

No comments:

Post a Comment