只读属性

时间:2009-08-24 10:54:04

标签: javascript variables object

是否可以将javascript对象属性设为只读?我想设置一个无法修改的属性......

3 个答案:

答案 0 :(得分:7)

这是可能的,但价格昂贵。你可以通过拥有一个真正的私有成员变量然后提供一个访问器函数来实现它:

var NiftyThing = function() {
    var trulyPrivateVariable;

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

这是有效的,因为访问器函数是对var的闭包。成本是每个实例都有自己的访问者函数副本。

编辑:用法:

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

有关详情,请参阅Private Member Variables in JavaScript

答案 1 :(得分:1)

你可以使用 Object.defineProperty()来实现这样的东西:

function blockProperties(object, properties) {
    "use strict";
    // If not properties passed, then use the already defined ones:
    if (typeof properties === "undefined") {
        properties = object;
    }
    // Loop trough the properties
    for (var property in properties) {
        if (properties.hasOwnProperty(property)) {
            // Make property read-only
            Object.defineProperty(object, property, {
                value: properties[property],
                writable: false,
                configurable: false,
                enumerable: false
            });
        }
    }
    return object;
}

var someObject = {};

blockProperties(someObject, {
    propertie1: "someValue",
    propertie2: "someOtherValue"
});

someObject.propertie1 = "this doesn't change anything";

console.log(someObject.propertie1); // Output: "someValue"

// Because "window" is also an object, you can set an only-read global var:
blockProperties(window, {
    onlyReadVariable: "onlyReadValue"
});

答案 2 :(得分:0)

我同意这个答案,并且想要注意一些像bob.js这样的JavaScript框架支持这样的内置机制:

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.

但是,如果您对属性有特殊需求,例如特定的get访问器实现需求,那么最好定义一个根据需要获取值的函数。

- 坦吉斯