Skip to content

Instantly share code, notes, and snippets.

@viettranx
Created August 26, 2018 18:08
Show Gist options
  • Save viettranx/348a00c82e75c8dc6ce7ed7da4d720fc to your computer and use it in GitHub Desktop.
Save viettranx/348a00c82e75c8dc6ce7ed7da4d720fc to your computer and use it in GitHub Desktop.
How to make a private variable in Class and prevent add/delete it with freeze and seal function.
// ES6
// A normal object
class iPhoneX {
secretName = 'iPhoneX'
constructor(price) {
this.price = price
}
setPrice = (value) => {
if (typeof value !== 'number' && value >= 1000)
throw new Error('Invalid price')
this.price = value
}
getName = () => `Apple ${this.secretName}`
}
// Everything works well but
cons ipx = new iPhoneX(1000)
ipx.price = 300 // we don't want price can be set directly
// Even worse
ipx.setPrice = () => 'Override done.'
ipx.setPrice() // Override done
ipx.secretName = '' // ops, we dont want public this variable
// So Freeze function comes to help
function Product(price) {
const secretName = 'iPhoneX'
const setPrice = (value) => {
if (typeof value !== 'number' && value >= 1000)
throw new Error('Invalid price')
price = value
}
const getPrice = () => price
const getName = () => `Apple ${this.secretName}`
return Object.freeze({setPrice, getPrice, getName})
}
const ipx = Product(1000) // no need 'new' keyword any more
console.log(ipx.getPrice()) // it's ok
ipx.setPrice(1100) // it's ok
ipx.price // undefined
ipx.setPrice = () => 'Try to re-assign' // it will not set
ipx.setPrice(2000) // still work
ipx.secretName // undefined
// Freeze function create a freezed object. Its properties and functions can not be re-assigned or deleted.
// We can do that with Seal function, but its properties and functions can be re-assigned.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment