最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - (obj || {}) vs Object(obj) - Stack Overflow

programmeradmin1浏览0评论

Are there any important differences (semantical, performance-related, etc.) between (1) and (2)?

  1. var obj = obj || {};
  2. var obj = Object(obj);

Context. The first is the way I've been sharing variables across Django's templates and my js files. I just came across a section in Rauschmayer 2014 ("Functions for Converting Boolean, Number, String, and Object", pg. 79), where he described Object(obj) as follows:

  • obj if obj is an object,
  • {} if obj is undefined or null,
  • [wrapped primitive] if obj is a primitive value.

Given that (very informal) semantics (particularly the first two clauses), it seems to me that we can use (2) wherever we would use (1), but I'm not entirely sure what consequences this will have.

Rauschmayer, Axel (2014) Speaking JavaScript (free to read online).

Are there any important differences (semantical, performance-related, etc.) between (1) and (2)?

  1. var obj = obj || {};
  2. var obj = Object(obj);

Context. The first is the way I've been sharing variables across Django's templates and my js files. I just came across a section in Rauschmayer 2014 ("Functions for Converting Boolean, Number, String, and Object", pg. 79), where he described Object(obj) as follows:

  • obj if obj is an object,
  • {} if obj is undefined or null,
  • [wrapped primitive] if obj is a primitive value.

Given that (very informal) semantics (particularly the first two clauses), it seems to me that we can use (2) wherever we would use (1), but I'm not entirely sure what consequences this will have.

Rauschmayer, Axel (2014) Speaking JavaScript (free to read online).

Share Improve this question asked Jul 11, 2015 at 19:55 ReadingtaoReadingtao 2331 silver badge5 bronze badges 1
  • 2 1 is a mon idiom, 2 is not. To make your code understandable to most programmers, stick with the usual syntax. – Barmar Commented Jul 11, 2015 at 19:58
Add a ment  | 

1 Answer 1

Reset to default 14

Yes there is a difference, as the quote you gave already mentions. The first notation will return the primitive itself when obj was a primitive. The second one will return a wrapped primitive, which is an object.

If the rest of the code relies on obj being an object, the second notation is more defensive.

But then again, the first notation is more mon, and one might wonder how a primitive value would be assigned to a variable named obj anyway.

发布评论

评论列表(0)

  1. 暂无评论