Last active
December 27, 2015 13:39
-
-
Save adrianvlupu/7334786 to your computer and use it in GitHub Desktop.
Getters/Setters in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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:'[email protected]'}); | |
o.name='adi'; | |
console.log(o.name); | |
o.email='[email protected]'; | |
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