工厂函数:为什么状态变量没有变为 "OK"?

Factory function: why doesn't status variable change to "OK"?

我正在从 javascript 类 切换到工厂函数。 除了参数,我还需要内部属性,例如。以下简化示例中的状态。那么,为什么 status 没有设置为 OK,应该如何设置?

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

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

return {name, status, setOK}

returns 具有这三个属性的对象,其值与返回对象时的值相同。如果你想要改变对象,而不是在 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);

Object Composition

使用Object.assign() to merge objects or "inherit" methods without using class or prototype. Composition 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);