Search
Learn
Share

JS: Object.defineProperty() example (a simple one)

Published by ivan on 8 August, 2017
7 views

Snippet

// Defining a constant, this value may not be re-assigned.
Object.defineProperty(window, 'SPEED_OF', {
value: {}
});

// https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Object.defineProperty(window.SPEED_OF, 'LIGHT', {
value: 299792458
});


// Let's play a bit.

function show_speed() {
console.log('Speed of light is ' + window.SPEED_OF.LIGHT + ' m/s.');
}

show_speed();

// The next two lines does not trow errors, but they are not effective though.
window.SPEED_OF = undefined;
window.SPEED_OF.LIGHT = 0;

show_speed();

Output

Speed of light is 299792458 m/s.
Speed of light is 299792458 m/s.