开发者

What is the result of the expression?

Does this code would work as expected in all browsers? Is there any notes in specificat开发者_C百科ion about it?

var attributes = this._attributes ? this._attributes : (this._attributes = []);

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.


There's nothing special about that expression, and you'll have no problems in any major browser. You could shorten it by using the || operator:

var attributes = this._attributes || (this._attributes = []);


That will work in all browsers.

It could be actually made terser with...

var attributes = this._attributes || (this._attributes = []);


No, I think unfortunately you may not access _attributes when it's undefined. So you have to check typeof attributes != "undefined".


I don't see any reason why not. I don't think I'd write it that way, I'm not a fan of assignments with side-effects, but syntactically it's fine.


This works just fine, when accessing an undefined property of any object, that access will return undefined. The single thing you have to watch out for is that you don't extend the Object.prototype to have a _attributes attribute because this will screw you up, but then again, never extend native prototypes.

From the spec :

8.12.2 [[GetProperty]] (P)

  1. Let prop be the result of calling the [[GetOwnProperty]] internal method of O with property name P.
  2. If prop is not undefined, return prop.
  3. Let proto be the value of the [[Prototype]] internal property of O.
  4. If proto is null, return undefined.
  5. Return the result of calling the [[GetProperty]] internal method of proto with argument P.

So it checks whether the object has the property, if so it returns it, if not it searches up the prototype chain, if it finds something there it returns it, otherwise it returns undefined.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜