The question is: Is it possible to create a structure like the folowing using object initializers in JavaScript?
var human = new function (years) {
var age = years;
Object.defineProperties(this, {
age: {
enumerable:true,
get: function () {
return age;
},
set: function (value) {
if( typeof value != 'number') throw 'Age must be a number';
age = value;
}
}
});
}
What I tried to do:
var years = 0;
var human = {
_age: years,
get age () {
return this._age;
},
set age (value) {
if( typeof value != 'number') throw 'Age must be a number';
this._age = value;
}
}
This example is more intuitive and “friendly” (for me at least), but I need that “_age” was local as it is in the previous example.
Is it possible to make local variables in object initializers?
you can do the following:
Another example: