1和new Number(1)有什么區別


1和new Number(1)有什么區別

author: @Tiffanysbear

總結,兩者的區別就是原始類型和包裝對象的區別。

什么是包裝對象

對象Number、String、Boolean分別對應數字、字符串、布爾值,可以通過這三個對象把原始類型的值變成(包裝成)對象:

var v1 = new Number(123);
var v2 = new String('abc');
var v3 = new Boolean(true);

我們來看下實際的v1、v2、v3是什么呢?

typeof v1;// "object"
typeof v2;// "object"
typeof v3;// "object"

v1 === 123; // false
v1 == 123; // true

可以理解的是,v1此時是對象,===比較的是內存地址,因此跟數字Number 123不相等;可是為什么v1 == 123得到的值會是true呢?

那這就是包裝對象在使用時的問題了。再來理解一下什么是原始類型。

什么是原始類型

比如123這類就是原始類型,原始類型並不是一個對象,因此並沒有對象具有的一些屬性和方法;但是為什么能調用(123).toFixed()這些方法呢?

原因就是這些方法都是像包裝對象"借用"來的,toFixed方法是在Number對象原型上的方法。

(123).toFixed === Number.prototype.toFixed // true
"123".indexOf === String.prototype.indexOf // true

JS求值

JS在求值運算時,總是會求出原始資料的值,而不是用對象。如下面的例子:

var a = new Number(122);
var b = a + 33; // 155
typeof b; // number

但是要注意 new Boolean 的用法,只有當 new Boolean 的參數值為 null 或者 undefined 時,求值轉換的原始資料的值才是false,其他情況都是true;

!!(new Boolean(false)) // true

所以盡量不要使用 new Boolean 這個包裝對象進行賦值,否則會產生一些誤會。

運算時調用 valueOf 和 toString 的優先級

先說下結論:

1、進行對象轉換時(alert(e2)),優先調用 toString 方法,如沒有重寫 toString 將調用 valueOf 方法,如果兩方法都不沒有重寫,但按 Object 的 toString 輸出。

2、進行強轉字符串類型時將優先調用 toString 方法,強轉為數字時優先調用 valueOf。

3、在有運算操作符的情況下,valueOf的優先級高於toString。

以下是三個例子

第一個:

let e2 = {
    n : 2,
    toString : function (){
        console.log('this is toString')
        return this.n
    },
    valueOf : function(){
        console.log('this is valueOf')
        return this.n*2
    }
}
alert(e2) //  2  this is toString
alert(+e2)  // 4 this is valueOf
alert(''+e2) // 4 this is valueOf
alert(String(e2)) // 2 this is toString
alert(Number(e2)) // 4 this is valueOf
alert(e2 == '4') // true  this is valueOf
alert(e2 === 4) //false ===操作符不進行隱式轉換


第二個:

let e3 = {
    n : 2,
    toString : function (){
        console.log('this is toString')
        return this.n
    }
}
alert(e3) //  2  this is toString
alert(+e3)  // 2 this is toString
alert(''+e3) // 2 this is toString
alert(String(e3)) // 2 this is toString
alert(Number(e3)) // 2 this is toString
alert(e3 == '2') // true  this is toString
alert(e3 === 2) //false  ===操作符不進行隱式轉換

第三個:

Object.prototype.toString = null; 
let e4 = {
    n : 2,
    valueOf : function(){
        console.log('this is valueOf')
        return this.n*2
    }
}
alert(e4) //  4 this is valueOf
alert(+e4)  // 4 this is valueOf
alert(''+e4) // 4 this is valueOf
alert(String(e4)) // 4 this is valueOf
alert(Number(e4)) // 4 this is valueOf
alert(e4 == '4') // true  this is valueOf
alert(e4 === 4) //false  ===操作符不進行隱式轉換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM