How to prevent the changing of a variable value in Javascript [duplicate]

*爱你&永不变心* 提交于 2019-12-03 06:55:35

Yes, there is. At least for object properties, ES5 gave us the possiblity to alter the property descriptor flags by hand. So we can do that like

var data = { };

Object.defineProperty(data, 'secret', {
    value: 42,
    writable : false,
    enumerable : true,
    configurable : false
});

That way, we created a property secret with the value 42 within data, which cannot get modfied nor deleted.

The caveat here is, that the genius (like you called it) will also be able to spot this code and just modify that, to again be able to change the content if he wishes to. You just can't create a secured front-end javascript in that way. The code will always be available as plain-text for everybody.


To make this more complete, you can also create an object and freeze it at some point, using Object.freeze() and/or Object.seal() to shutdown the option for enumerating, deleting and modifying on properties of an object.

But again the word of caution: This is intended to affect your own code or foreign code, to prevent modifications by accident or on purpose at run time. There is no way to stop a developer since he can simply halt the execution of your script, before this even can take affect.

try the const keyword. it should create an immutable variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!