Copyright (c) 2019-
Author: Chaitanya Tejaswi (github.com/CRTejaswi) License: MIT
Example: Create a data/accessor property
- Data Property
var car = {};
Reflect.defineProperty(car, "make", {
value: "Honda",
writeable: true,
configurable: true,
enumerable: true
});
Reflect.defineProperty(car, "model", {
value: "City",
writeable: true,
configurable: true,
enumerable: true
});
Reflect.defineProperty(car, "year", {
value: 2008,
writeable: true,
configurable: true,
enumerable: true
});
car.make = "Suzuki"; car.model = "Wagon-R"; car.year = 2013;
console.table(car);
┌─────────┬─────────┐
│ (index) │ Values │
├─────────┼─────────┤
│ make │ 'Honda' │
│ model │ 'City' │
│ year │ 2008 │
└─────────┴─────────┘
- Accessor Property
var car = { __make__: "Honda",
__model__: "City",
__year__: 2008
};
Reflect.defineProperty(car, "make", {
get: function(){
return this.__make__;
},
set: function(newMake){
this.__make__ = newMake;
},
configurable: true,
enumerable: true
});
Reflect.defineProperty(car, "model", {
get: function(newModel){
return this.__model__;
},
set: function(newModel){
this.__model__ = newModel;
},
configurable: true,
enumerable: true
});
Reflect.defineProperty(car, "year", {
get: function(newYear){
return this.__year__;
},
set: function(newYear){
this.__year__ = newYear;
},
configurable: true,
enumerable: true
});
car.make = "Suzuki"; car.model = "Wagon-R"; car.year = 2013;
console.table(car);
┌───────────┬───────────┐
│ (index) │ Values │
├───────────┼───────────┤
│ __make__ │ 'Suzuki' │
│ __model__ │ 'Wagon-R' │
│ __year__ │ 2013 │
│ make │ 'Suzuki' │
│ model │ 'Wagon-R' │
│ year │ 2013 │
└───────────┴───────────┘