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

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

问题描述


可能重复:

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


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

解决方案

实际上......不要覆盖它。您总是可以通过将其包装在仅提供没有SetObj的GetObj的对象中来控制访问,但当然,包装器同样可以覆盖,因为它的私有成员属性将通过GetObj方法隐藏。



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



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



编辑:



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

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

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

var hider = new objectHider(someData);

// ... hider.getObject()

其中参考在objectHider中obj



我试图想到实际用途。

Possible Duplicate:
Can Read-Only Properties be Implemented in Pure JavaScript?

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

解决方案

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:

Can Read-Only Properties be Implemented in Pure JavaScript?

EDIT:

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()

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天全站免登陆