且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Javascript中创建变量/对象?

更新时间:2023-11-15 12:05:40

实际上......不要覆盖它。您总是可以通过将其包装在仅提供没有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.