简体   繁体   English

只读属性

[英]read-only property

Is it possible to make a javascript object property read-only? 是否可以将javascript对象属性设为只读? I want to set a property that cannot be modified... 我想设置一个无法修改的属性...

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. 这是有效的,因为访问器函数是对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. 有关更多信息,请参阅JavaScript中的私有成员变量

You can implement something like this, making use of Object.defineProperty() : 你可以使用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"
});

I agree with the answer, and would like to note that some JavaScript frameworks like bob.js support such built-in mechanisms: 我同意这个答案,并且想要注意一些像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.

However, if you have special needs regarding property, such as specific get accessor implementation needs, then better define a function which gets the value as you need it. 但是,如果您对属性有特殊需求,例如特定的get访问器实现需求,那么最好定义一个根据需要获取值的函数。

- Tengiz - Tengiz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM