Last active
August 29, 2015 14:06
-
-
Save eordano/93e42fc74d76e19c7e5c to your computer and use it in GitHub Desktop.
Defining read only values in JS
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
por qué sería necesario pasarle el getter a
defineReadOnlyProperty
?Sería cómodo hacer:
o me estoy perdiendo de algo?