在Javascript中'冻结'数组? [英] 'Freezing' Arrays in Javascript?

查看:100
本文介绍了在Javascript中'冻结'数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ECMA-262规范,Javascript获得了 Object.freeze()方法,该方法允许添加或删除其属性无法更改的对象。

Since the ECMA-262 specifications Javascript has gained the Object.freeze() method, which allows for objects, whose properties can not be changed, added or removed.

var obj = {'a':1, 'b:2'};
Object.freeze(obj);
Object.isFrozen(obj);       // returns true
obj.a = 10;                 // new assignment has no affect
obj.a;                      // returns 1

到目前为止一切顺利。

我想知道,freeze()是否也适用于数组。

I am wondering, whether freeze() should also work on Arrays.

var arr = [1, 2];
Object.freeze(arr);
Object.isFrozen(arr);      // returns true
arr[0] = 10;
arr;                       // returns [10, 2] ... ouch!

也许我错了,但我的印象是,Array继承自Object。

Maybe I am wrong, but I was under the impression, that Array inherits from Object.

typeof obj                 // "object"
typeof arr                 // "object"

任何想法,指示,启示都将受到高度赞赏。

Any ideas, pointers, enlightenments would be highly appreciated.

推荐答案

是的,冻结应该适用于Arrays,您遇到的行为显然是一个实现错误。

Yes, freeze should work for Arrays, the behavior you are experiencing is clearly an implementation bug.

此错误可能与数组对象实现的事实有关自定义 [[DefineOwnProperty]] 内部方法(使长度属性工作的魔力。)

This bug might be related to the fact that array objects implement a custom [[DefineOwnProperty]] internal method (the magic that makes the length property work).

我刚刚在两个实现上测试它并且它正常工作( Chrome 16.0.888和Firefox Aurora 8.02a)。

I just tested it on two implementations and it works properly (Chrome 16.0.888, and Firefox Aurora 8.02a).

关于第二个问题,数组对象继承自 Array.prototype 继承自 Objec例如,你可以直接在数组对象上从 Object.prototype 访问非阴影方法:<​​/ p>

About your second question, well, array objects inherit from Array.prototype which inherits from Object.prototype, for example, you can access non shadowed methods from Object.prototype directly on array objects:

['a'].hasOwnProperty('0'); // true

但这与类型的方式无关有效,此运算符将为任何对象intance返回'object',无论其类型如何,以及 null 值,人们一直抱怨。

But this isn't related about how the typeof works, this operator will return 'object' for any object intance, regardless its kind, and for the null value, which people has always complained about.

typeof 运算符的其余可能返回值,对应于语言的原始类型,数字,字符串,布尔值,符号和未定义。

The rest of possible return values of the typeof operator, correspond to the primitive types of the language, Number, String, Boolean, Symbol and Undefined.

这篇关于在Javascript中'冻结'数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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