簡體   English   中英

工廠功能:為什么狀態變量不更改為“ OK”?

[英]Factory function: why doesn't status variable change to “OK”?

我正在從javascript類切換到工廠功能。 除了參數,我還需要內部屬性,例如。 以下簡化示例中的狀態。 那么,為什么狀態沒有設置為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}

返回具有這三個屬性的對象,其值與返回該對象時的值相同 如果要更改對象,請事先在Model內定義該對象,然后在setOKsetOK對象進行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.assign()合並對象或“繼承”方法,而無需使用classprototype 組成重於繼承


演示

演示中詳細評論

 /* 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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM