可以只读属性的纯JavaScript实施? [英] Can Read-Only Properties be Implemented in Pure JavaScript?

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

问题描述

纵观 Mozilla的文档,看着正规前$​​ P $ pssion例子(标题为创建使用比赛的结果数组),我们有这样的语句:

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:

输入:一个只读属性,反映其对正规前pression被匹配原始字符串

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

指数:只读属性,它匹配字符串中的索引(从零开始)

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,在新的浏览器的支持。见<一href=\"http://stackoverflow.com/questions/366047/can-read-only-properties-be-implemented-in-pure-javascript/2964881#2964881\">Aidamina's回答。如果你需要支持老的浏览器,你可以使用的方法之一,这个答案作为后备。

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,歌剧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.

您可以阅读更多关于它从约翰Resig的博客或<一个href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters\">Mozilla开发者中心。

You can read more about it from John Resig's blog or the Mozilla Developer Center.

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

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