Make a property that is read-only to the outside world, but my methods can still set

后端 未结 3 432
眼角桃花
眼角桃花 2020-12-28 08:49

In JavaScript (ES5+), I\'m trying to achieve the following scenario:

  1. An object (of which there will be many separate instances) each with a read-only property
3条回答
  •  误落风尘
    2020-12-28 09:23

    I've been doing this lately:

    // File-scope tag to keep the setters private.
    class PrivateTag {}
    const prv = new PrivateTag();
    
    // Convenience helper to set the size field of a Foo instance.
    function setSize(foo, size)
    {
      Object.getOwnPropertyDiscriptor(foo, 'size').set(size, prv);
    }
    
    export default class Foo
    {
      constructor()
      {
        let m_size = 0;
        Object.defineProperty(
          this, 'size',
          {
            enumerable: true,
            get: () => { return m_size; },
            set: (newSize, tag = undefined) =>
            {
              // Ignore non-private calls to the setter.
              if (tag instanceof PrivateTag)
              {
                m_size = newSize;
              }
            }
          });
      }
    
      someFunc()
      {
        // Do some work that changes the size to 1234...
        setSize(this, 1234);
      }      
    }
    

    I think that covers all of the OP's points. I haven't done any performance profiling. For my use cases, correctness is more important.

    Thoughts?

提交回复
热议问题