Defining read-only properties in JavaScript

前端 未结 5 810
广开言路
广开言路 2020-11-28 06:23

Given an object obj, I would like to define a read-only property \'prop\' and set its value to val. Is this the proper way to do that?

5条回答
  •  暖寄归人
    2020-11-28 06:59

    Because of the old browsers (backwards compatibility) I had to come up with accessor functions for properties. I made it part of bob.js:

    var obj = { };
    //declare read-only property.
    bob.prop.namedProp(obj, 'name', 'Bob', true);
    //declare read-write property.
    bob.prop.namedProp(obj, 'age', 1);
    
    //get values of properties.
    console.log(bob.string.formatString('{0} is {1} years old.', obj.get_name(), obj.get_age()));
    //set value of read-write property.
    obj.set_age(2);
    console.log(bob.string.formatString('Now {0} is {1} years old.', obj.get_name(), obj.get_age()));
    
    //cannot set read-only property of obj. Next line would throw an error.
    // obj.set_name('Rob');
    
    //Output:
    //========
    // Bob is 1 years old.
    // Now Bob is 2 years old.
    

    I hope it helps.

提交回复
热议问题