Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to prevent replacement of JavaScript object properties?

I would like to make an object's structure immutable, preventing its properties from being subsequently replaced. The properties need to be readable, however. Is this possible?

I'm sure there are no language features (along the lines of final in Java and readonly in C#) to support this but wondered whether there might be another mechanism for achieving the same result?

I'm looking for something along these lines:

var o = {
    a: "a",
    f: function () {
        return "b";
    }
};

var p = o.a;        // OK
o.a = "b";          // Error
var q = o.f();      // OK
o.f = function () { // Error
    return "c"; 
};
like image 352
Matthew Murdoch Avatar asked Mar 02 '10 17:03

Matthew Murdoch


2 Answers

You can now force a single object property to be frozen instead of freezing the whole object. You can achieve this with Object.defineProperty and the parameter writable: false

var obj = {
    "first": 1,
    "second": 2,
    "third": 3
};
Object.defineProperty(obj, "first", {
    writable: false,
    value: 99
});

In this example, obj.first now has its value locked to 99.

like image 99
jaggedsoft Avatar answered Sep 18 '22 08:09

jaggedsoft


the best thing you can do is hide your properties inside of a closure.

var getMap = function(){
  var hidden = "1";
  return {
    getHidden : function() { return hidden; }
  }
}

var f = getMap ();

alert(f.getHidden());

I took a stab at it. In the above code you will need to not just return hidden but copy it into a new object perhaps. maybe you can use jquery's extend to do this for you, so you will be returning a new object, not the reference. This may be completely wrong though =)

like image 20
mkoryak Avatar answered Sep 22 '22 08:09

mkoryak