Skip to content

Instantly share code, notes, and snippets.

@eordano
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eordano/93e42fc74d76e19c7e5c to your computer and use it in GitHub Desktop.
Save eordano/93e42fc74d76e19c7e5c to your computer and use it in GitHub Desktop.
Defining read only values in JS
var defineReadOnlyProperty = function(object, propertyName, getter) {
Object.defineProperty(object, propertyName, {
getter: getter,
setter: function () { throw new Error('Invalid access'); }
});
};
function MyClass() {
var props = {
esta: 1,
another: 2
};
_.each(props, function(value, key) {
defineReadOnlyProperty(this, key, function() { return props[key]; );
});
}
MyClass.prototype.aMethod = function() { return this.esta; };
var e = new MyClass();
e.esta // 1
e.aMethod() // 1
e.another // 2
@matiu
Copy link

matiu commented Sep 5, 2014

por qué sería necesario pasarle el getter a defineReadOnlyProperty ?

Sería cómodo hacer:

setReadyOnly(this,key);

o me estoy perdiendo de algo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment