Pages

Friday, 8 June 2012

JavaScript Create Getters and Setters

Here is an easy and simple way to create getters and setters in JavaScript.

1. Creating variables to store values


Create a variable named '_' which is an object that will hold all the other variables. Then create a variable called x which equals to '0'.

var _ = {
   x:0
}

2. Create a function which can get and set a variable.


function x(value)
{

       if(value==undefined)return _.x ;
       _.x = value;

}

This function can return the variable 'x' if a parameter is not passed into it but if you pass in a parameter is will store it.

3. Test it



console.log(x());
x(5);
console.log(x());


The variable value starts as 0 then we provide the function with a value of 5 and the output changes accordingly.

No comments:

Post a Comment