I need a way to define a getter
inside a class constructor, I want to store and get a variable defined outside the class but unique to the instance. Here's what I have in mind:
// this works fine
const uniqueID = 5
class Person {
get id() {
return uniqueID
}
constructor(element){
// do the dew with element
console.log( this.id + ' ' + element )
}
}
This is fine to have a property that's not in this
instance object, but it's not specific to the instance, here's the thing:
// this won't work
let uniqueID = 1
function getUnique(element){
return element.uniqueID || uniqueID++
}
class Person {
constructor(element){
const elementID = getUnique(element)
element.uniqueID = elementID
Object.defineProperty(Person, 'id', { get: () => elementID } )
// any of the below also fail
// Object.defineProperty(Person.prototype, 'id', { get: () => elementID } )
// Object.defineProperty(Person.constructor, 'id', { get: () => elementID } )
// Object.defineProperty(this, 'id', { get: () => elementID } )
// do the dew with element
console.log( this.id + ' ' + element )
}
}
Any of the above throw Uncaught TypeError: Cannot redefine property: id
, but I can set whatever property name, like myUniqueID
, it's the same error.
The NEED is that I have to set a UNIQUE ID specific to the element without storing the ID in this
instance, which is important to not expose the ID unless allowed to or internally called.
Please feel free to ask further clarification and thanks in advance for any reply.