zoukankan      html  css  js  c++  java
  • javascript于"return obj === void 0"这样的书面理由和优势

    得知underscore.js什么时候,查看源代码经常出现的类别似下面的代码:

    if (context === void 0) return func;
    
    if (array == null) return void 0;

    曾经没有见过这样的写法。到网上搜了一些资料。刚好发现stackoverflow上也有人提出类似的疑问。这里总结归纳下。做个笔记。

    void事实上是javascript中的一个函数,接受一个參数,返回值永远是undefined。能够说,使用void目的就是为了得到javascript中的undefined。Sovoid 0 is 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


     

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    Linux网卡上添加多个IP
    TCP_Wrappers基础知识介绍
    工作、生活、思考、人生、经验、总结
    网络层安全
    centos7.0 安装nginx
    linux 下配置jdk
    yii2.0 中的队列
    centos7.0 activemq的安装
    solrCloud
    线性顺序表
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4757201.html
Copyright © 2011-2022 走看看