Skip to content

Instantly share code, notes, and snippets.

@naoxink
Created July 17, 2018 08:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save naoxink/971ee8e2ad092937241bce1046e18a75 to your computer and use it in GitHub Desktop.
`Object.defineProperty` calculated property test
function addVirtualProperty(options){
if(!options.obj || typeof options.obj !== 'object'){
throw new Error('Expected `obj`[Object object]')
}
if(!options.prop){
throw new Error('Expected `prop`')
}
Object.defineProperty(options.obj, options.prop, {
get(){
return options.getter.call(options.obj)
},
set(value){
options.setter.call(options.obj, value)
}
})
}
// TEST
var user = {
'firstName': 'Vincent',
'lastName': 'Vega'
}
addVirtualProperty({
'obj': user,
'prop': 'fullName',
'getter': function(){
return this.firstName + ' ' + this.lastName
},
'setter': function(value){
value = value.split(' ')
this.firstName = value[0]
this.lastName = value[1]
}
})
console.log(a.firstName)
console.log(a.lastName)
console.log(a.fullName)
console.log('-----------')
a.fullName = 'Jules Winnfield'
console.log(a.firstName)
console.log(a.lastName)
console.log(a.fullName)
console.log('-----------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment