Home  >  Article  >  Web Front-end  >  How to use js to protect variables from being modified at will

How to use js to protect variables from being modified at will

一个新手
一个新手Original
2017-10-06 10:42:252470browse


/** 1.如果在renderTitle,renderContent里面,这样总数据谁都能修改,不安全
* 改进
* 1.规定一个专门修改数据的方法,如果想修改数据只能走这个方法
*
* action代表一个命令对象,就是一个普通的js对象,起码需要一个字段控制命令类型type,其他字段随意
*
* */const CHANGE_FONT_SILE='CHANGE_FONT_SILE';//设置一个闭包,把变量保护起来,通过返回值调用function createStore() {
    let appState={
        fontSize:'26px',
        title:{
            text:'标题',
            color:'red'
        },
        content:{
            text:'类容',
            color:'green'
        }
    }    //保护变量被修改,深克隆
    let getState=()=>JSON.parse(JSON.stringify(appState));    //改变变量的方法
    let dispatch=(action)=>{        
        switch(action.type){            
        case CHANGE_FONT_SILE:
                appState.fontSize=action.fontSize;            
                default:                
                return;
        }
    }    //返回出去的修改和取值的接口
  return{
      getState,
      dispatch
  }
}

let store=createStore();//取值函数function renderTitle() {
    let titleEle = document.querySelector('#title');

    titleEle.innerHTML = store.getState().title.text;
    titleEle.style.color = store.getState().title.color;
    titleEle.style.fontSize = store.getState().fontSize;
}function renderContent() {
    let titleEle=document.querySelector("#content");
    titleEle.innerHTML=store.getState().content.text;
    titleEle.style.color=store.getState().content.color;
    titleEle.style.fontSize=store.getState().fontSize;
}function renderApp() {
    renderTitle();
    renderContent()
}//修改appState里面初始值,单独一个修改文件store.dispatch({type:CHANGE_FONT_SILE,fontSize:'30px'})
renderApp();

The above is the detailed content of How to use js to protect variables from being modified at will. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn