> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/methods-of-primitives.md).

# Methods of primitives

## A primitive as an object

JavaScript 作者遇到的難題：

* 人們想用方法對原始值做很多事情。
* 原始值必須要輕量且快速。

解決方法如下：

* 原始值仍為原始值，只能儲存單一值。
* 語法允許原始值有方法、屬性，如同物件一樣。
* 當使用這些方法時，JavaScript 提供特殊的包裝物件，執行完畢便會消失。

```javascript
// string method
let str = "Hello";
alert( str.toUpperCase() ); // HELLO

// number method
let n = 1.23456;
alert( n.toFixed(2) ); // 1.23
```

* 當使用 `toUpperCase()` ，JavaScript 創造一個特殊包裝物件，
* 方法執行並返回運算結果。
* 特殊包裝物件消失，原本的 str 仍然存在。

### &#x20;Constructors `String/Number/Boolean` are for internal use only

Javascript 允許創造特殊包裝物件的建構函式 `String/Number/Boolean` 但高度不建議這樣做。

```javascript
// create new wrapper-object
alert( typeof 0 ); // "number"
alert( typeof new Number(0) ); // "object"!

let zero = new Number(0);
if (zero) { // zero is true, because it's an object
  alert( "zero is truthy!?!" );
}

// type convert
let num = Number("123"); // convert a string to number
```

### null/undefined have no methods

`null` and `undefined` 沒有特殊包裝物件。

```javascript
alert(null.test); // error
```
