Examplet Center

Javascript Examplets and Examples

Select the following Topics you are interested

  1. List of all Javascript Examplets and Examples

Javascript Examplet - Add property to Javascript Object in "jQuery" style

This "Javascript examplet" is extracted from article "Add property to Javascript Object in "jQuery" style" from Cloudgen's Javascript Laboratory

 


Statement of Goal

To allow adding an encapsulated property to a JSON arbitrary, with "chainable" setter and getter function using the same name, which are similar to JQquery's functions.

 


Snippet:

The following is the source code of the snippet. Click the link for downloading the snippet.

<script type="text/javascript">
(function($){
    $.property=function(name, predicate){
		var value;
		this[name]=function(e){
			if(typeof e=="undefined") return value;
			if(predicate && !predicate(e)) throw "property "+name + " have been assigned with invalid value: " +e;
			else value = e;
			return this
		};
		return this;
	}
})(Object.prototype); //Object prototype
CheckRules={
        STRING:function(x){return typeof x=="string";},
        NUMBER:function(x){return typeof x=="number";}
        // You can add your own rules here
};

</script>

Application Note:

The following is the application code of the snippet.

<script type="text/javascript">
var a={};
a.property("age",CheckRules.NUMBER).property("name",CheckRules.STRING).age(12).name("Cloudgen");
document.getElementById("output").innerHTML="My name:"+a.name()+"<"+"br/>"+"My age:"+a.age()+"<"+"br/>";

</script>

Output:


Copyright 2010 Cloudgen Wong