Skip to content

Instantly share code, notes, and snippets.

@adrianvlupu
Last active December 27, 2015 13:39
Show Gist options
  • Save adrianvlupu/7334786 to your computer and use it in GitHub Desktop.
Save adrianvlupu/7334786 to your computer and use it in GitHub Desktop.
Getters/Setters in javascript
//method 1
var A = function(name){
var _name = name;
Object.defineProperty(this, 'name', {get: function(){console.log('get name'); return _name;},
set:function(e){console.log('set name='+e); _name=e;},
enumerable: true
});
return this;
};
var B = new A('instance1');
var C = new A('instance2');
console.log(B);
console.log(C);
//method 2
var o = {};
Object.defineProperty(o, 'name', {get: function(){console.log('get o.name'); return this._name;},
set:function(e){console.log('set o.name='+e); this._name=e;},
enumerable: true
});
Object.defineProperty(o, 'email', {value:'test@test.ro'});
o.name='adi';
console.log(o.name);
o.email='email@test.ro';
console.log(o.email);
console.log(o);
//method 3
var city = {
_location : 'X',
get location () {
console.log('get location');
return this._location;
},
set location(val) {
console.log('set location');
this._location = val;
},
_name : 'defaultName',
get name () {
console.log('get name');
return this._name;
},
set name(val) {
console.log('set anme');
this.name = val;
}
};
console.log(city.location);
city.location = "Bucharest";
console.log(city.location);
console.log(city.name);
console.log(city);
//method 4
var city = function() {
var _location = 'X';
return {
get location () {
console.log('get location');
return _location;
},
set location(val) {
console.log('set location');
_location = val;
}
};
};
var b = new city();
var c = new city();
console.log(b.location);
b.location = "Bucharest";
console.log(b.location);
console.log(b);
console.log(c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment