• js中有包装类,java中也有包装类


    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
     
  • 相关阅读:
    C#之事件
    C#之委托
    CIC许可更新
    HMP许可更新
    知识库上传
    [转]spring中<tx:advice></tx:advice>意义
    [转]spring property标签中的 ref属性和ref 标签有什么不同
    [转] Spring@Autowired注解与自动装配
    [转]SpringMVC入门
    [转]SpringMVC拦截器详解[附带源码分析]
  • 原文地址:https://www.cnblogs.com/oxspirt/p/8678639.html
Copyright © 2020-2023  润新知