Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read-only property

Is it possible to make a javascript object property read-only? I want to set a property that cannot be modified...

like image 559
mck89 Avatar asked Feb 28 '23 09:02

mck89


1 Answers

It's possible, but expensive. You can do it by having a truly private member variable and then providing an accessor function:

var NiftyThing = function() {
    var trulyPrivateVariable;

    trulyPrivateVariable = 5; // For instance
    this.accessorFunction = function() {
        return trulyPrivateVariable;
    }
};

That works because the accessor function is a closure over the var. The cost is that each instance has its own copy of the accessor function.

EDIT: Usage:

var n = new NiftyThing();
alert(n.trulyPrivateVariable);
// Alerts "undefined"
alert(n.accessorFunction());
// Alerts "5"

See Private Member Variables in JavaScript for more.

like image 62
T.J. Crowder Avatar answered Mar 07 '23 07:03

T.J. Crowder