JavaScript protection variables are not arbitrarily modified------elegant programming

Source: Internet
Author: User

/** 1. If in rendertitle,rendercontent, such total data who can modify, unsafe * improved * 1. Specify a method to modify the data, if you want to modify the data can only go this method * * Action represents a Command object, is a normal JS object, at least need a field control command type types, other fields feel free * **/Const Change_font_sile= ' Change_font_sile ';//set a closure, protect the variable, and call it by the return value .functionCreateStore () {Let appState={fontSize:' 26px ', title:{text:Title, Color:' Red '}, content:{text:' Class capacity ', Color:' Green '        }    }    //protection variables are modified, deep clonesLet getstate= () =Json.parse (Json.stringify (appState)); //ways to change variablesLet dispatch= (action) ={        Switch(action.type) { CaseCHANGE_FONT_SILE:appState.fontSize=action.fontsize; default:                return; }    }    //returns the interface for modifying and fetching values  return{getState, dispatch}}let store=createstore ();//Accessor value functionfunctionRendertitle () {Let Titleele= Document.queryselector (' #title '); Titleele.innerhtml=store.getstate (). Title.text; TitleEle.style.color=store.getstate (). Title.color; TitleEle.style.fontSize=store.getstate (). fontSize;}functionrendercontent () {Let Titleele=document.queryselector ("#content"); Titleele.innerhtml=store.getstate (). Content.text; TitleEle.style.color=store.getstate (). Content.color; TitleEle.style.fontSize=store.getstate (). fontSize;}functionRenderapp () {rendertitle (); Rendercontent ()}//Modify the appstate inside the initial value, a single modified fileStore.dispatch ({type:change_font_sile,fontsize: ' 30px '}) Renderapp ();

JavaScript protection variables are not arbitrarily modified------elegant programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.