简体   繁体   中英

JavaScript: Create Function that returns a function that returns output with getter / setter capabilities

I am trying to create a function that has setter and getter capabilities.

Below are my test specs.

it('the returned function can get properties of the given object', () => {
    let accessObject = accessor({ a: 100 });
    expect(accessObject('a')).toEqual(100);

    accessObject = accessor({ foobar: [7, 8, 9] });
    expect(accessObject('foobar')).toEqual([7, 8, 9]);
    expect(accessObject('a')).toEqual(undefined);
  });

  it('the returned function can set properties of the given object', () => {
    const obj = { stuff: 'something' };
    const accessObject = accessor(obj);

    accessObject('stuff', 'a new value');
    expect(obj.stuff).toEqual('a new value');

    expect(obj['pizz-pie']).toEqual(undefined);
    //              key       value
    accessObject('pizza-pie', 'yummmm');
    expect(obj['pizza-pie']).toEqual('yummmm');
  });
});

The code below passes my test specs but I am confused by why, specifically on the setter portion of my code.

const accessor = obj => {
  return (prop, value) => {
    if (value === undefined) {
      return obj[prop];
    } else {

      // QUESTION: what is going on here?  
      return obj[prop] = value;
    }
  };
};

Please see my question commented in my code above.

Without a value passed as a parameter, then your code acts like a getter. Otherwise, it acts as a setter buy returning the property value immediate after setting it.

You can think of this being written this way alternatively;

if (value === undefined) {
  return obj[prop];
} else {
  obj[prop] = value;
  return obj[prop];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM