可以在纯 JavaScript 中实现只读属性吗? [英] Can Read-Only Properties be Implemented in Pure JavaScript?

查看:18
本文介绍了可以在纯 JavaScript 中实现只读属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 mozilla 文档,查看正则表达式示例(标题为使用匹配结果创建数组"),我们有如下语句:

Looking at the mozilla documentation, looking at the regular expression example (headed "Creating an array using the result of a match"), we have statements like:

输入:反映正则表达式匹配的原始字符串的只读属性.

input: A read-only property that reflects the original string against which the regular expression was matched.

index:一个只读属性,它是字符串中匹配项的从零开始的索引.

index: A read-only property that is the zero-based index of the match in the string.

等...是否可以在 JavaScript 中创建您自己的具有只读属性的对象,或者这是为特定浏览器实现的内置类型保留的特权?

etc... is it possible to create your own object in JavaScript which will have read-only properties, or is this a privilege reserved to built-in types implemented by particular browsers?

推荐答案

自从编写此答案以来,使用 Object.defineProperty 的一种新的更好的方法已经在 EcmaScript 5 中标准化,并支持较新的浏览器.请参阅艾达米娜的回答.如果您需要支持旧"浏览器,您可以使用本答案中的一种方法作为后备.

Since this answer was written, a new, better way using Object.defineProperty has been standardized in EcmaScript 5, with support in newer browsers. See Aidamina's answer. If you need to support "older" browsers, you could use one of the methods in this answer as a fallback.

在 Firefox、Opera 9.5+ 和 Safari 3+、Chrome 和 IE(使用 v11 测试)中,您可以定义 getter 和 setter 属性.如果您只定义一个 getter,它会有效地创建一个只读属性.您可以在对象字面量中或通过调用对象的方法来定义它们.

In Firefox, Opera 9.5+, and Safari 3+, Chrome and IE (tested with v11) you can define getter and setter properties. If you only define a getter, it effectively creates a read-only property. You can define them in an object literal or by calling a method on an object.

var myObject = {
    get readOnlyProperty() { return 42; }
};

alert(myObject.readOnlyProperty); // 42
myObject.readOnlyProperty = 5;    // Assignment is allowed, but doesn't do anything
alert(myObject.readOnlyProperty); // 42

如果你已经有一个对象,你可以调用__defineGetter____defineSetter__:

If you already have an object, you can call __defineGetter__ and __defineSetter__:

var myObject = {};
myObject.__defineGetter__("readOnlyProperty", function() { return 42; });

当然,这在网络上并不是很有用,因为它在 Internet Explorer 中不起作用.

Of course, this isn't really useful on the web because it doesn't work in Internet Explorer.

您可以从John Resig 的博客Mozilla 开发者中心.

这篇关于可以在纯 JavaScript 中实现只读属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆