Search code examples
javascriptjavascript-objects

Question about Javascript: Can I assign two names to the same member?


I have a set of objects, that contain references to other objects. There is always a general reference: nextObject. But sometimes, I know more about the object beside me. So I could use a member like: theNextSentenceInThisParagraph.

Some code, that knows what they are dealing with, could use tNSITP. Other code, that doesn't know about the adjacent object, would use nO. I could assign two members, each with its own name, pointing to the adjacent object. But I'd rather assign two names to the same member. Is that possible?

myObject
    nextObject: theNextSentenceInThisParagraph: reference-to-next-object

Solution

  • Sure, but not with the syntax you're proposing. What you're looking for is get and/or set:

    const obj = {
      foo: 0,
      get bar() {
        return this.foo;
      },
      set bar(value) {
        this.foo = value;
      },
    };
    
    console.log('foo', obj.foo);
    console.log('bar', obj.bar);
    
    obj.foo = 1;
    
    console.log('foo', obj.foo);
    console.log('bar', obj.bar);
    
    obj.bar = 2;
    
    console.log('foo', obj.foo);
    console.log('bar', obj.bar);