Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function addProtectedVar(object, name, validator){
- if (! typeof(object) == "object")
- throw new Error("Object required for the first argument!");
- if (name.length == 0)
- throw new Error("Set name of variable to the second argument!");
- if (validator && (typeof(validator)!="function"))
- throw new Error("Third argument must be a function!");
- if (validator && validator.length != 1)
- throw new Error("Validator function must receive 1 argument!");
- camel_name = name.charAt(0).toUpperCase() + name.substr(1);
- if (object.hasOwnProperty('set' + camel_name) || object.hasOwnProperty('get' + camel_name))
- throw new Error("Object already has method/property set" + camel_name + ' or get' + camel_name);
- functions = (function(name, validator){
- var property;
- var variable_name = name;
- return {
- get:function(){
- return property;
- },
- set:function(value){
- if (validator){
- if (validator(value))
- property = value;
- else
- throw new Error("Wrong value for \"" + variable_name + "\" property!");
- }else{
- property = value;
- }
- }
- };
- })(name,validator);
- object["get" + camel_name] = functions["get"];
- object["set" + camel_name] = functions["set"];
- }
- var object = {x:1, y:2};
- try{
- addProtectedVar(object, 'secret', function(val){return val > 0});
- addProtectedVar(object, 'secret2', function(val){return (val % 2) == 0});
- addProtectedVar(object, 'secret3', function(val){return (val % 2) == 0});
- object.setSecret(12);
- object.getSecret(); // 12
- object.setSecret2(4);
- }catch(e){
- console.error(e);
- }
Advertisement
Add Comment
Please, Sign In to add comment