Showing posts from March, 2015

Mutator methods in Javascript

A Mutator method is used to control changes to a variable, which is formerly known asgetter and setter methods. Several server side languages supports Mutator methods. Lets see how to achieve the same in JavaScript. There are some restrictions to achieve it in obsolete browsers. Lets see the different ways to implement mutator methods in JavaScript,

Method 1: Exposing our own getter and setter methods
function User(){ this._name = ''; this.getName = function(){ return 'Hey ' + this._name; } this.setName = function(name){ this._name = name } } var u1 = new User(); u1.setName('Ajai') console.log(u1.getName()) //Hey Ajai
Method 2: Using ES5 Syntax (supported in all ES5 ready browsers)
//with Prototype function User(){ this._name = ''; } User.prototype = { get name(){ return 'Hey ' + this._name; }, set name(name){ this._name = name; } } var u1 = new User(); = "Ajai" console.log( //Hey Ajai //without Proto…