What is Boolean.valueOf in JavaScript

Typeof of Boolean.valueOf is a function, but what does it do? Why do object versions of primitives have methods such as Array.valueOf? This is not the same as, for example, Boolean.prototype.valueOf ...

That the point Boolean.toString () simply returns this: "function Boolean () {[native code]}". There are also other objects like Array, Number ...

+4
source share
2 answers

Why is this happening

Boolean- a feature like Stringand Objectyou can call it as a function to convert something into a logical, for example:

Boolean(3); // true

JavaScript , .valueOf. Boolean - , valueOf . Object#valueOf ,

alert(Boolean.valueOf() === Boolean) // true

// for the same reason
var x = {};
alert(x.valueOf() === x); // true
Hide result

:

15.2.4.4 Object.prototype.valueOf

O - ToObject, .

:

9.9 ToObject

- ( ).

.valueOf . ( , , .toString). , Number .

:

3 == {valueOf: function() {return 3; }}//true

4 < {valueOf: function() {return 2; }}//false

Math.max(3, {valueOf: function() {return 5;}})//5,

, , JavaScript , ES7 .

+8

, .valueOf .toString .

JavaScript valueOf . valueOf ; JavaScript , .

valueOf , Object. , .

.valueOf , . . , , .valueOf .

, Boolean.toString() : "function Boolean() {[native code]}".

Boolean.toString(), Boolean.prototype.toString() . .toString , :

var bool = true;

console.log(bool.toString()); // "true"

, JS ( +).

. toString.

+2

All Articles