Metaprogramming in JavaScript/TypeScript Part #1

Descriptor.

JavaScript / TypeScript meetaprogramming

Descriptor

let apt = {
floor: 12,
number: '12B',
size: 3400,
bedRooms: 3.4,
bathRooms: 2,
Price: 400000,
amenities: {...}
};
let descriptor = Object.getOwnPropertyDescriptor(apt, ‘floor’); console.log(descriptor);// Output
{
value: 12,
writable: true,
enumerable: true,
configurable: true
}
Object.defineProperty(apt, ‘floor’, {writable: false});
apt.floor = 44;
console.log(apt.floor);
// output
12

” Cannot assign to read only property ‘floor’ of object ‘…

Object.defineProperty(apt, ‘floor’, {writable: false, configurable: false});
Object.defineProperty(apt, ‘floor’, {writable: true, configurable: true});

“TypeError: Cannot redefine property: floor…”

//This can be done when initialising the property:
Object.defineProperty(apt, ‘floor’, {value: 12, writable: false, configurable: false});
//Or after the initialisation:
Object.defineProperty(apt, ‘floor’, {writable: false, configurable: false});
class Apartment {
constructor(apt) {
this.apt = apt;
}

getFloor() {
return this.apt.floor
}
}

let apt = {
floor: 12,
number: '12B',
size: 3400,
beds: 3.4,
baths: 2.
};
Apartment.prototype.getFloor = () => {
return 44.
};
let myApt = new Apartment(apt);
console.log(myApt);
// output will be changed.
44
Object.defineProperty(Apartment.prototype, 'getFloor',
{writable: false, configurable: false});
Apartment.prototype.getFloor = () => {
return 44.
};
let myApt = new Apartment(apt);
console.log(myApt);
// output will be original.
12

Back to enumerable.

let otherApt = {
floor: 12,
number: '12B',
size: 3400,
bedRooms: 3.4,
bathRooms: 2,
price: 400000,
amenities: {}
};

let keys = Object.keys(otherApt);
console.log(keys);
// Output
['floor', 'number', 'size', 'bedRooms',
'bathRooms', 'price', 'amenities']
Object.defineProperty(otherApt, 'amenities', {enumerable: false});
const keys = Object.keys(otherApt);
console.log(keys);
// Output
[ 'floor', 'number', 'size', 'bedRooms', 'bathRooms', 'price']
console.log(otherApt.hasOwnProperty(‘amenities’));
// Output
true

Takeaway

--

--

Web development expert and teams manager with over twenty years experience in the industry.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel Ostrovsky

Web development expert and teams manager with over twenty years experience in the industry.