Created
July 17, 2018 08:44
Star
You must be signed in to star a gist
`Object.defineProperty` calculated property test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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