工厂功能:为什么状态变量不更改为“ OK”?

时间:2019-03-10 10:08:09

标签: javascript function factory

我正在从javascript类切换到工厂功能。 除了参数,我还需要内部属性,例如。以下简化示例中的状态。那么,为什么状态未设置为“确定”,应该怎么做?

const Model = (name) => {
    name = "myname";
    let status = "initial";

    const setOK = () => {
        status = "OK";
    }
    return {name, status, setOK}
};

const m = Model();
console.log(m.status); //status is initial
m.setOK();
console.log(m.status);  //expecting OK, but still initial

2 个答案:

答案 0 :(得分:2)

当前,返回的对象永远不会改变:您的

return {name, status, setOK}

返回具有这三个属性的对象,其值为返回对象时的值。如果要更改对象,请事先在Model内定义该对象,然后在setOK内对该对象进行突变:

const Model = (name) => {
  name = "myname";
  let status = "initial";
  const setOK = () => {
    obj.status = "OK";
  };
  const obj = { name, status, setOK };
  return obj;
};

const m = Model();
console.log(m.status);
m.setOK();
console.log(m.status);

答案 1 :(得分:0)

Object Composition

使用Object.assign()合并对象或“继承” 方法,而无需使用classprototypeComposition over inheritance


演示

演示中评论的详细信息

/* 
Object monitor has setOK() method. 
Note the parenthesis wrapped around the curly braces ensures
that the object literal will be invoked as a expression.
The props object from Model is passed to monitor object
*/
const monitor = props => ({
  setOK: () => {
    props.status = "OK";
  }
});

/* Factory Function 
Note the object literal props. props will be passed through
Object.assign() method in order to inherit the method setOK() from the monitor object.
*/
const Model = name => {
  let props = {
    name: name,
    status: "initial"
  };
  return Object.assign(props, monitor(props));
};

// Create object m with the name: "checkStatus"
const m = Model("checkStatus");
// Verify object m is named "checkStatus"
console.log('name: '+m.name);
// Check status
console.log('status: '+m.status);
// Invoke .setOK() method
m.setOK();
// Check status
console.log('status: '+m.status);