Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
`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
You can’t perform that action at this time.