new Number() vs Number()

What is the difference between new Number() and Number()? I get that new Number() creates a Number object and Number() is just a function, but when should I call which, and why?

On a related note, Mozilla says:

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task.

x = Boolean(expression);     // preferred
x = new Boolean(expression); // don't use

Why is that? I thought the results were the same?

-----------------------------------------------------------------------------------------------

40down voteaccepted

Boolean(expression) will simply convert the expression into a boolean primitive value, while new Boolean(expression) will create a wrapper object around the converted boolean value.

The difference can be seen with this:

// Note I'm using strict-equals
new Boolean("true") === true; // false
Boolean("true") === true; // true

And also with this (thanks @hobbs):

typeof new Boolean("true"); // "object"
typeof Boolean("true"); // "boolean"

Note: While the wrapper object will get converted to the primitive automatically when necessary (and vice versa), there is only one case I can think of where you would want to use new Boolean, or any of the other wrappers for primitives - if you want to attach properties to a single value. E.g:

var b = new Boolean(true);
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // will work var b = true;
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // undefined
answered Jan 18 '11 at 0:19
David Tang

71.5k23141134
 

最新文章

  1. 当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式。
  2. HTML5桌面通知:notification
  3. htm.dropdownlist
  4. angular router-ui
  5. 全球最低功耗蓝牙单芯片(DA14580)系统架构和应用开发框架分析
  6. ASP.NET-FineUI开发实践-11
  7. Keil C51中变量和函数的绝对地址定位问题
  8. 一个页面从输入URL到页面加载显示完成的详细过程
  9. TF-IDF与余弦相似性的应用(一):自动提取关键词 - 阮一峰的网络日志
  10. 表单提交是ajax提交,PC提交没问题但是手机提交就会一直跳到error,并且也没状态码一直是0
  11. [学习笔记]15个QA让你快速入门51单片机开发
  12. Java 8 Streams filter examples
  13. OpenGL基本框架与三维对象绘制
  14. BZOJ 2460: [BeiJing2011]元素
  15. WKInterfaceTable实例化出现的一系列
  16. es查询,聚合、平均值、值范围、cardinality去重查询
  17. Kali渗透测试工具-netcat
  18. PHP文件环境搭建—EcShop环境搭建
  19. HDU 6216 A Cubic number and A Cubic Number【数学思维+枚举/二分】
  20. ffmpeg初体验

热门文章

  1. Python操作12306抢票脚本
  2. 如何用纯 CSS 创作一个菱形 loader 动画
  3. Vue 2.0 项目在IE下显示空白
  4. 《零基础入门学习Python》【第一版】视频课后答案第003讲
  5. Google 超分辨率技术 RAISR
  6. Hi3519V101 SDK安装以及开发环境搭建
  7. HDU 3506 DP 四边形不等式优化 Monkey Party
  8. 大数据学习——Storm+Kafka+Redis整合
  9. Cocos2d-JS 实现将TiledMap中的每个 tile 变成物理精灵的方法
  10. 使用python实现简单的爬虫