简体   繁体   English

JavaScript:创建函数,该函数返回一个返回具有getter / setter功能的输出的函数

[英]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. 我正在尝试创建一个具有setter和getter功能的函数。

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. 如果没有将value作为参数传递,那么您的代码就像一个吸气剂。 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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