Domanda

How can I Create such object.
The object should have a name once the name is set it cannot be modified.

var movies = {
    genre:"Horror";
    }
movies.genre= "Pop" I dont want to change my genre value
È stato utile?

Soluzione

You can actually change the properties of an object.

I found this after some researching, modify it to your needs.

var data = { };

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

From @jAndy's answer:

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.

Source: How to prevent the changing of a variable value in Javascript

Altri suggerimenti

You can try to use Object.defineProperty with descriptor option and writable attribute:

var o = {}; // Creates a new object

Object.defineProperty(o, "a", { value : 37,
                                writable : false });

console.log(o.a); // logs 37
o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
console.log(o.a); // logs 37. The assignment didn't work.

Below approach should work across all browsers including older ones.

You can use closure and immediately invoked functions (IIFE) to achieve private properties. Below is a sample code. Here the initial value is passed as a param to IIFE. The IIFE initializes private property with init value and then returns an object containing accessor function for the private property. Since the returned object doesn't directly have the private property on it, it cannot be modified however it is accessible through closure.

var objWithPrivateProp = (function(initValue){
   var privateProp = initValue;
   return {
      getPrivateProp: function () {
          return privateProp;
      }
   };
})("Horror");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top