ECMAScript 5 has get/set properties creation [ Object.defineProperty() ]
however I find this is still too fragile - you can try to get the value for a non-existing property, with no error.
so here is some code to make get/set functions for a property, which can be more robust:
however I find this is still too fragile - you can try to get the value for a non-existing property, with no error.
so here is some code to make get/set functions for a property, which can be more robust:
/** @description Try to create robust code to get/set a property
*/
var createRobustProperty = function (target, name) {
//NOT using Object.defineProperty since it means client still can call non-existent get property -> 'undefined' result!
target['get' + name] = function() {
return target['_' + name];
};
target['set' + name] = function(value) {
target['_' + name] = value;
};
};
//test:
var Car = function() {
createRobustProperty(this, 'Color');
};
var c1 = new Car();
c1.setColor('red');
console.log('car color = ' + c1.getColor());
//c1.getcolor() //error - no such property!
Comments
Post a Comment