Created
September 14, 2011 09:27
-
-
Save neoGeneva/1216184 to your computer and use it in GitHub Desktop.
C# like properties 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
var createProperty = function(getSet) { | |
var _value; | |
var autoImplement = { | |
get: function() { return _value; }, | |
set: function(value) { _value = value; return _value; } | |
}; | |
getSet = getSet || autoImplement; | |
var get = getSet.get || function() { throw new Error('No get method defined for this property.'); }, | |
set = getSet.set || function() { throw new Error('No set method defined for this property.'); }; | |
return function(value) { | |
if (value !== undefined) | |
return set(value); | |
return get(); | |
}; | |
}; |
Well, what I was looking for something like:
myClass.customProperty = 123; // sets value
var value = myClass.customProperty; // gets value
Note the difference from the last two lines of your example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: