建立的是物件, 不是純值
有時候JavaScript engine會把純值包到物件中給你使用, 這樣你可以取用你可能需要的屬性或方法
var a = new Number(3) //印出Number{[[PrimitiveValue]] : 3} console.log(a) Number.prototype var a = new String("John")
為內建的函數建構子擴充方法
//原型中的this會指向物件 String.prototype.isLengthGreaterThan = function(limit) { return this.length > limit; } //字串被自動轉換為物件, 並取用物件的方法 console.log("John".isLengthGreaterThan(3)) //數字不會被轉換為物件 Number.prototype.isPositive = function(){ return this > 0; } //發生錯誤 3.isPositive(); var a = new Number(3); //true a.isPositive();
Last updated 4 years ago
Was this helpful?