简体   繁体   中英

Are Read-Only Properties in Javascript Objects REALLY Read-Only?

I know that it's possible to create a read-only object in Javascript with code similar to this (sorry, "borrowed it" from another thread):

var obj = {};
Object.defineProperty( obj, "<yourPropertyNameHere>", {
  value: "<yourPropertyValueHere>",
  writable: false,
  enumerable: true,
  configurable: true
});

But as a Java developer, I know that I can use reflection to change a field that is declared as private. What I need to know is this: is it possible to prevent a malicious end-user from changing a read-only variable declared in the manner above?

Edit: Okay, I get it. This was a component of, not the entirety of, an entire security infrastructure. All inputs from the client-side to the server-side will be validated at the server side (I'm not a total idiot). But I want to explore the possibility of doing SOMETHING to make the client aware of the backend security infrastructure (roles assigned, etc).

This question has only one answer, never trust js. Even thought you can declare it, there is no way to be sure the user won't change the hole object. The way to avoid the user tampering with your variables is using closure. Just define a function, declare all your variables, and run that function. There is a shorthand for that:

(function () {
    //Your code, DECLARE ALL YOUR VARIABLES WITH "var variableName"
    //i.e.
    var myNumber = 3, myString = 'Hello World', myEmptyVar;
})();

Take a look at 'use strict' (strict mode) and use jshint for better coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM