Select the following Topics you are interested
This "Javascript examplet" is extracted from article "One line properties setter and getter for Javascript class" from Cloudgen's Javascript Laboratory
To allow adding an encapsulated property and shared property to a Javascript class arbitrary, with "chainable" setter and getter function using the same name, which are similar to JQquery's functions.
The following is the source code of the snippet. Click the link for downloading the snippet.
<script type="text/javascript">
(function($){
function property(obj,name, predicate,e){
var value=e;
obj[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 obj;
};
return obj;
}
$.property=function(name,predicate){
this.prototype[name]=function(e){
property(this,name,predicate,e);
return this;
};
return this
}
$.sharedProperty=function(name, predicate){
var value;
this.prototype[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
};
})(Function.prototype); //Function prototype
CheckRules={
STRING:function(x){return typeof x=="string";},
NUMBER:function(x){return typeof x=="number";}
// You can add your own rules here
}
</script>
The following is the application code of the snippet.
<script type="text/javascript">
function Person(){};
Person.property("age",CheckRules.NUMBER).property("name",CheckRules.STRING).sharedProperty("familyName",CheckRules.STRING);
var a=new Person();
var b=new Person();
a.name("C. F.").age(20).familyName("Wong");
b.name("Cloudgen").age(23);
document.write("My name is "+a.name()+", my age is "+a.age()+". I come from "+ a.familyName()+"'s family<"+"br/>");
document.write("My name is "+b.name()+", my age is "+b.age()+". I come from "+ b.familyName()+"'s family<"+"br/>");
</script>