如何在 Javascript 中使变量/对象只读? [英] How can you make a variable/Object read only in Javascript?

查看:21
本文介绍了如何在 Javascript 中使变量/对象只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
可以在纯 JavaScript 中实现只读属性吗?

我有一个对象,我只想在构造时定义它.如何防止对象引用被更改?

I have an Object that I only want to be defined when constructed. How can I prevent the Object reference from being changed?

推荐答案

这是 10 年前写的.我不认为这是一个最新的答案.

实际上......通过不覆盖它.您始终可以通过将它包装在一个只提供 GetObj 而没有 SetObj 的对象中来控制访问,但是当然,包装器同样容易被覆盖,它的私有"对象也是如此.将隐藏"的成员属性通过 GetObj 方法.

Realistically... by not overwriting it. You could always control access by wrapping it in an object that only offers GetObj with no SetObj, but of course, the wrapper is equally liable to overwriting, as are its "private" member properties that would be "hidden" via the GetObj method.

实际上,问题是一个骗局:

Actually, question is a dupe:

可以在纯 JavaScript 中实现只读属性吗?

阅读 http://javascript.crockford.com/private.html 后,它可以使用闭包来创建外部世界真正无法访问的变量引用.例如:

After reading http://javascript.crockford.com/private.html , it is possible to use closure to create variable references that are truely inaccessible from the outside world. For instance:

function objectHider(obj)
{
    this.getObject=function(){return obj;}
}

var someData={apples:5,oranges:4}

var hider=new objectHider(someData);

//... hider.getObject()

其中 objectHider 中对 obj 的引用在对象创建后无法修改.

where the reference to obj in objectHider cannot be modified after object creation.

我正在尝试为此考虑一个实际用途.

I'm trying to think of a practical use for this.

这篇关于如何在 Javascript 中使变量/对象只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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