Saturday, 24 March 2012

C# Object Initializers in JavaScript

A very short entry for a trick I came up with today

I'm rather keen on C#'s Object Initializers, and it's something that to some degree I've been missing in JavaScript. I'm saying just "to some degree" because on many occasions in JavaScript we just have enough with Object Literals and don't go down the way of declaring a "constructor" function and adding functions to the prototype (maybe we don't intend to have more than one instance of that object)...

Anyway, what could be the equivalent to this C#'s code:

Person p = new Person{
Name = "xose",
Age = 36
};

Well, jQuery's extend function comes more than handy here, so we can write this:

//constructor function
function person(){
...
}

var p = $.extend(new person(),{
name: "xose",
age : 36
};
Very simple, but so helpful...

No comments:

Post a Comment