Home > Web Front-end > JS Tutorial > body text

Examples of JavaScript implementations that protect variables from being modified at will

黄舟
Release: 2017-09-28 11:08:45
Original
1369 people have browsed it

This article uses example code to share with you the implementation method of JavaScript protecting variables from being modified at will. Friends who need it can refer to it

Let me share the code with you below:


/*
* 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();
Copy after login

Summary

The above is the detailed content of Examples of JavaScript implementations that protect variables from being modified at will. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!