开发者

JavaScript: Adding properties to a sealed object should throw a typeerror exception?

开发者 https://www.devze.com 2023-02-20 19:44 出处:网络
Suppose I\'ve got something like this in JavaScript: var obj = { name: \"Luis\" }; Object.seal( obj ); obj.address = \"Fx\"; //what should happen here?

Suppose I've got something like this in JavaScript:

var obj = { name: "Luis" };
Object.seal( obj );

obj.address = "Fx"; //what should happen here?

So, what's the correct behavior? It's not in strict-mode, so I assumed that obj.address line would simply be ignored. However, that is not the case since it throws in Chrome. I'm looking at the tests for V8 and it seems like it should only throw in strict-mode:

object.seal test code: http://code.开发者_StackOverflowgoogle.com/p/v8/source/browse/branches/bleeding_edge/test/mjsunit/object-seal.js?spec=svn7379&r=7379

and here's some code from that file:

Object.seal(obj);

// Make sure we are no longer extensible.
assertFalse(Object.isExtensible(obj));
assertTrue(Object.isSealed(obj));

// We should not be frozen, since we are still able to
// update values.
assertFalse(Object.isFrozen(obj));

// We should not allow new properties to be added.
obj.foo = 42;
assertEquals(obj.foo, undefined);

btw, there are the tests from strict mode, where my example will clearly throw: http://code.google.com/p/v8/source/browse/branches/bleeding_edge/test/mjsunit/strict-mode.js?spec=svn7250&r=7250

Any ideas?


Object.seal does 2 things.

1) Sets objects's internal [[Extensible]] attribute to false.

2) Iterates over all of object's own properties and sets their internal [[Configurable]] attribute to false.

This pretty much means that you can't add any properties to an object after it's being sealed. Note that existing properties can still be modified, as long as an object is not frozen (or if a property that's being assigned to is not made non-writable explicitly).

In your case, you're adding another property to a sealed object, so in ES5-non-strict it should be ignored whereas in ES5-strict it should result in TypeError (as you can see from 11.3.1 (Simple Assignment); more specifically you can track it down to [[CanPut]] which pretty much returns the value of [[Extensible]] — false — in this case, and then [[Put]] either throws, if it's strict mode, or doesn't).

So nope, Chrome should not be throwing here (in non-strict mode).


IE9: doesn't throw
Chrome: throws
Firefox 4: trows only in strict-mode code

0

精彩评论

暂无评论...
验证码 换一张
取 消