javascript于"return obj === void 0"这样的书面理由和优势
2015-08-25 13:39
701 查看
得知underscore.js什么时候,查看源代码经常出现的类别似下面的代码:
曾经没有见过这样的写法。到网上搜了一些资料。刚好发现stackoverflow上也有人提出类似的疑问。这里总结归纳下。做个笔记。
void事实上是javascript中的一个函数,接受一个參数,返回值永远是undefined。能够说,使用void目的就是为了得到javascript中的undefined。So
为什么不直接使用undefined呢?主要有2个原因:
1、使用void 0比使用undefined可以降低3个字节。尽管这是个优势。个人但感觉意义不大,牺牲了可读性和简单性。
2、undefined并非javascript中的保留字,我们能够使用undefined作为变量名字,然后给它赋值。
Because of this, you cannot safely rely on undefined having the value that you expect。
void, on the other hand, cannot be overidden. void 0 will always return。
我在IE10,Firefox和chrome下測试。遗憾的是没有出现预期的结果。尽管上面的代码没有报错,可是并没有打印出我们期望的"new value"。
所以整体来说。使用void 0这样的写法意义不大。
參考
http://stackoverflow.com/questions/7452341/what-does-void-0-mean
http://stackoverflow.com/questions/11409412/how-to-understand-return-obj-void-0-in-the-source-of-underscore
if (context === void 0) return func; if (array == null) return void 0;
曾经没有见过这样的写法。到网上搜了一些资料。刚好发现stackoverflow上也有人提出类似的疑问。这里总结归纳下。做个笔记。
void事实上是javascript中的一个函数,接受一个參数,返回值永远是undefined。能够说,使用void目的就是为了得到javascript中的undefined。So
void 0is a correct and standard way to produce
undefined.
void 0 void (0) void "hello" void (new Date()) //all will return undefined
为什么不直接使用undefined呢?主要有2个原因:
1、使用void 0比使用undefined可以降低3个字节。尽管这是个优势。个人但感觉意义不大,牺牲了可读性和简单性。
>"undefined".length 9 >"void 0".length 6
2、undefined并非javascript中的保留字,我们能够使用undefined作为变量名字,然后给它赋值。
alert(undefined); //alerts "undefined" var undefined = "new value"; alert(undefined) //alerts "new value"
Because of this, you cannot safely rely on undefined having the value that you expect。
void, on the other hand, cannot be overidden. void 0 will always return。
我在IE10,Firefox和chrome下測试。遗憾的是没有出现预期的结果。尽管上面的代码没有报错,可是并没有打印出我们期望的"new value"。
所以整体来说。使用void 0这样的写法意义不大。
參考
http://stackoverflow.com/questions/7452341/what-does-void-0-mean
http://stackoverflow.com/questions/11409412/how-to-understand-return-obj-void-0-in-the-source-of-underscore
相关文章推荐
- JSP中的两种注释方式
- json字符串转成字典
- jackJson的基本用法2___map-json 与 json-map
- jackJson的基本用法1___obj-json 与 json-obj
- js方法格式化数字,加入千分符,并可以指定小数点位数
- wg_listToTree小插件 用 javascript 将List数组转换为Tree
- js常见的一些错误
- 【转】理解与使用Javascript中的回调函数
- 基于JavaScript分析property 和 attribute
- 【JavaScript】--原型
- iframe中子父类窗口调用JS的方法及注意事项
- JS学习之事件冒泡
- 问题:JsonConvert;结果:JSON详解
- JavaScript+CSS实现仿天猫侧边网页菜单效果
- jsoi2008最大数bzoj1012
- 奔跑吧,我的JavaScript(2)
- JS使用键盘左右箭头进行翻页
- js常用正则表达式
- Jsp 中out.println()为什么不换行
- javascript表单验证之SQL注入验证