I was discussing a few things with a good friend several days ago and some of the things I have learned and conceptualized recently are very interesting with tons of capabilities being unlocked. Here I discuss how to use JSON to make a simple object that looks cleaner than the normal fashion of Javascript objects and resembles Java for ease of translation. As with all of my other posts that I write on javascript, you will notice that there are similarities in that I always use JQuery for the simple reasoning of not wanting to put code in my view/html. Additionally, this is an HTML document, though it will work in traditional and strict forms of the newer HTML standards as well. This is just a demo and description.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
//<!--
// This is a simple javascript object where you have anAttribute,
// then it's setter and getter
var simpleObject = {
"anAttribute":"Hello World",
"getAnAttribute":function(){return this.anAttribute},
"setAnAttribute":function(newAttributeValue)
{
this.anAttribute = newAttributeValue
}
};
// Code block of jQuery to interact with our object.
// this is equal to $(document).ready(function(){});
$(function(){
// Add the original attribute to the demo div
$("#demo").html(simpleObject.getAnAttribute());
// Change anAttribute, using the setter
simpleObject.setAnAttribute("Hi There");
// Now let's alert anAttribute to prove that it has changed
alert(simpleObject.getAnAttribute());
});
//-->
</script>
</head>
<body>
This is a simple demo to show how sweet Javascript Object Notation (JSON) really is.
<div id="demo"></demo>
</body>
</html>
Personally, I think getters and setters are old school but necessary when the need arises to encapsulate business logic. In this particular example, there is no “business logic” which means little reason to use accessors though we will for translation and demonstration.
Notice the call to getAnAttribute() first to set the value of html in our “demo” div. The latter is a simple alert. The point is, at this point in time, the same attribute equals different values.
This has been tested on Chrome, IE 8 and Firefox.
So why is this useful? I guess the first place that I see this used most often is in jQuery plugins, this is also the place that I started using it when I first began writing jQuery plugins many moons ago. Secondly, I really like to write public APIs for web applications and was trying to concept a way to really simplify one of my APIs down to nothing for consumers.
So to recap, the benefits.
- Useful when writing jQuery plugins
- Easier and more powerful APIs
- Cleaner than the “Old School” way of creating javascript objects
- Very portable with current libraries
Currently I am at a loss for the drawbacks, leave them in comments if you have any.