Created
December 16, 2010 09:58
-
-
Save kompozer/743244 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Getter and setter | |
var TEST = (function(exposed) { | |
// Underbar method | |
var User = exposed.User = function() { | |
this._name = 'teste'; // readonly | |
} | |
User.prototype = (function() { | |
function private() { | |
this._name = 'im private'; | |
} | |
return { | |
get name() { return this._name }, | |
changeName: function () { | |
private.call(this); | |
} | |
} | |
})(); | |
// __define*etter__ method | |
var Person = exposed.Person = function() { | |
var name = 'Person'; | |
this.__defineGetter__("name", function() { | |
return name; | |
}); | |
this.__defineSetter__("name", function(val) { | |
name = val; | |
}); | |
} | |
return exposed; | |
})(TEST || {}); | |
(function() { | |
var a = new TEST.User(); | |
var b = new TEST.User(); | |
console.info('a.name ' + a.name); | |
console.info('b.name ' + b.name); | |
b.changeName(); | |
console.info('a.name ' + a.name); | |
console.info('b.name ' + b.name); | |
// b.name = 'test'; // wont work! | |
console.info('---'); | |
var c = new TEST.Person(); | |
var d = new TEST.Person(); | |
console.info('d.name ' + c.name); | |
console.info('d.name ' + d.name); | |
d.name = 'test'; | |
console.info('c.name ' + c.name); | |
console.info('d.name ' + d.name); | |
})(); | |
// Benchmarks about getter and setter | |
// http://united-coders.com/christian-harms/javascript-object-property-getter-benchmarks-part-2 | |
// http://united-coders.com/christian-harms/javascript-object-access-micro-benchmarks |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment