Regroup your JavaScript function using JSON
Posted by Nordes on November 19th, 2008 filed in JavaScript, ProgrammingIn JavaScript we have the opportunity to create object using JSON and we should use that opportunity for clarity of code. By example, if you want to have a call to a function that load something and return something else, you can do something like this:
var Math = { Add: function(Number1, Number2) { /// /// Addition function. /// /// Return the total of two number (n1 + n2). Code here. }, Sub: function(Number1, Number2) { /// /// Substract function. /// /// Return the total of two number (n1 – n2). Code here. }, ... }
To call your function, you can simply call it by doing “alert(Math.Add(12,12));”. It is also possible to create object where you need to do a new to instantiate it. To learn more about the JSON, you can go on http://msdn.microsoft.com/en-us/library/bb299886.aspx.
If you want to instantiate an object that does some init stuff, I strongly suggest using something like the following:
var Math = function { init stuff here ... Create function directly inside the function (anonymous type) function Sub(Number1, Number2) { /// /// Substract function. /// /// Return the total of two number (n1 – n2). Code here. } } function Math.prototype.Add (Number1, Number2) { /// /// Addition function. /// /// Return the total of two number (n1 + n2). Code here. }
It actually looks more like a class that you need to instantiate. By example to use the previous code, you need to do:
var myMathObj = new Math(); var addResult = myMathObj.Add(10,14); var subResult = myMathObj.Sub(15,10);
Here’s a link to a good tutorial about the prototype: http://www.javascriptkit.com/javatutors/proto.shtml.
June 15th, 2009 at 3:06 am
The article is usefull for me. I’ll be coming back to your blog.
October 25th, 2009 at 9:37 pm
inchim lesbian invariant tempers seed granting sitesthe allocates centreaie alcoholic thirdly acme
October 29th, 2009 at 4:24 pm
context divvy birman ecdl hierarchies rene palestinians sturgeon vires executive detailing