Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Created December 24, 2021 10:19
Show Gist options
  • Save mitchallen/f653a2705df87708e0990beaa59c08fd to your computer and use it in GitHub Desktop.
Save mitchallen/f653a2705df87708e0990beaa59c08fd to your computer and use it in GitHub Desktop.
JavaScript object getter and setter
function factory() {
let value = 42;
return {
get price() { return value },
set price( p ) {
value = p;
}
}
}
let product = factory();
let log = (msg) => console.log( product.price, msg );
log('original price');
product.price = 45;
log('price set');
product.price++;
log('price incremented');
product.price += 5;
log('price increase by x');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment