Skip to content

如何实现一个只读属性?

  1. Object.defineProperty

    js
    const obj = {}
    Object.defineProperty(obj, 'name', {
      value: 'foo',
      wirtable: false,
    })

    或者,另外一种写法:

    js
    Object.defineProperty(obj, 'name', {
      get() {
        return 'foo'
      },
    })
  2. Proxy

    js
    const obj = {}
    const handler = new Proxy(obj, {
      get() {
        return 'foo'
      },
    })
  3. Object.freeze

    js
    const obj = {
      name: 'foo',
    }
    Object.freeze(obj)
    // 不过需要注意,这种方式会导致对象的所有东西都不能更改了

基于 MIT 许可发布