首页 > 解决方案 > 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 很重要,除非允许或内部调用。

请随时要求进一步澄清,并提前感谢您的任何回复。

标签: javascriptprivate-keyes6-class

解决方案


推荐阅读