javascript - ES6 在类构造函数中定义 getter
问题描述
我需要一种getter
在类构造函数内部定义的方法,我想存储并获取在类外部定义但对实例唯一的变量。这是我的想法:
// 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
实例对象中的属性很好,但它不是特定于实例的,事情是这样的:
// 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 )
}
}
以上任何一个 throw Uncaught TypeError: Cannot redefine property: id
,但我可以设置任何属性名称,例如myUniqueID
,这是相同的错误。
需要的是我必须设置一个特定于元素的唯一 ID,而不在this
实例中存储 ID,这对于不公开 ID 很重要,除非允许或内部调用。
请随时要求进一步澄清,并提前感谢您的任何回复。
解决方案
推荐阅读
- database - 如何从第一种形式的选定行中过滤另一种形式的表格?
- composer-php - 403 Forbidden 您无权访问此服务器上的 /drupal Drupal 8
- jquery - 如何解析具有重复节点的 XML?
- sql - 添加导致 GROUP BY 错误的聚合列
- javascript - PHP 为 D3 生成 JSON
- outlook-redemption - 调用outlook redemption 64位
- c# - 在 C# 中返回一个对象
- installation - 在代理后面安装 Tensorflow 时遇到问题
- python - 使用数据驱动页面时从图例中删除最后一个字符串值
- pysnmp - pysnmp getcmd 超时不起作用