Introduction to the horrible valueOf method in JS

Source: Internet
Author: User

Peng Laoshi mentioned the valueOf method in his recent monthly report. He was excited to go over the introduction of the valueOf method in ECMA5, as follows:

15.2.4.4 Object. prototype. valueOf ()
When the valueOf method is called, the following steps are taken:
1. Let O be the result of calling ToObject passing the this value as the argument.
2. If O is the result of calling the Object constructor with a host object (15.2.2.1), then
A. Return either O or another value such as the host object originally passed to the constructor. The specific result that is returned is implementation-defined.
3. Return O.
The description of valueOf in the specification is very short. It is roughly called the ToObject method (an abstract method, which will be discussed later) and passed in the value of this as a parameter.

For different parameters (this) passed in when ToObject is called, the return values are as follows:Below:

1. When this is the host object, the returned value depends on the implementation of the browser, that is, the return of different browsers may be different (for the host object, refer to the http://www.w3school.com.cn/js/pro_js_object_types.asp)
2. If this is not the host object, the value of ToObject (this) is returned.

Parameter type Returned results
Undefined A TypeError is thrown.
Null A TypeError is thrown.
Number Create a Number object. Its internal initial value is the passed parameter value.
String Create a String object. Its internal initial value is the input parameter value.
Boolean Create a Boolean object. Its internal initial value is the passed parameter value.
Object Return input parameters (no conversion)

According to the definition of Object. prototype. valueOf and the description of the abstract method ToObject, the following table is available.
Obj type Object. prototype. valueOf. call (obj) returned results
Undefined A TypeError is thrown.
Null A TypeError is thrown.
Number Number Type object with the value equal to obj
String String type object with the value equal to obj
Boolean Boolean object with the same value as obj
Object Obj object itself

For example:
Copy codeThe Code is as follows:
Var num = 123;
Console. log (num. valueOf (); // output: 123
Console. log (num. valueOf (); // output: 'number'

Var unde = undefined;
Console. log (Object. prototype. valueOf. call (unde); // output: 'typeerror: Cannot convert null to Object'

Var obj = {name: 'casper '};
Var linkObj = obj. valueOf ();
LinkObj. name = 'change ';
Console. log (linkObj. name); // output: 'change'... description obj. valueOf () returns the object itself

In fact, the Array and Function objects are not mentioned above. According to the following code, we can guess that when the Object. prototype. when valueOf is called, when the parameter is an Array or Function object, the returned result is also the object itself:
Copy codeThe Code is as follows:
Var arr = [1, 2, 3];
Var linkArr = arr. valueOf ();
LinkArr [0] = ['casper '];
Console. log (linkArr); // output: ['casper ', 2, 3]

Var foo = function () {return 1 ;};
Var linkFoo = foo. valueOf ();
LinkFoo. test = 'casper ';
Console. log (linkFoo. test); // output: 'casper'

After reading the above description, is there a sudden sensation? If yes, congratulations. Maybe you haven't fully understood it yet, just like me.

For example, if the Object that calls Object. prototype. valueOf is of the numerical type, assuming that the Object is named num, num may be declared in the following two ways:
Copy codeThe Code is as follows:
Var num = 123; // declare console. log (typeof num) through the object literal; // output: 'number'
Var num = new Number (123); // declare console. log (typeof num) through the constructor; // output: 'object'

For more abnormal declaration methods, see the five unknown methods for declaring Number in JS.

Description of returned values: the original text in ECMA5 is as follows::

Create a new Number object whose [[PrimitiveValue] internal property is set to the value of the argument. See 15.7 for a description of Number objects.
According to the description in this section, it seems that num. valueOf () should return a Number object (which is not a literal Declaration), but in fact:
Copy codeThe Code is as follows:
Var num = 123;
Var tmp = num. valueOf ();
Console. log (typeof tmp); // output: 'number'

What's going on? So I looked at it carefully and it seemed that it was a little close to the truth:
5.7.4.4 Number. prototype. valueOf ()

Returns this Number value.

The valueOf function is not generic; it throws a TypeError exception if its this value is not a Number or a Number object. therefore, it cannot be transferred to other kinds of objects for use as a method.
The original Number has its own prototype valueOf method, instead of directly inheriting from Object. prototype. Similarly, Boolean and String also have its own prototype valueOf method, which is summarized as follows:
Type Does the valueOf method belong to its own prototype?
Undefined None
Null None
Number Yes, Number. prototype. valueOf
String Yes, String. prototype. valueOf
Boolean Yes, Boolean. prototype. valueOf
Object -
In addition, Array and Function do not have their own prototype valueOf method. For more information, see specifications:

NOTE The Array prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the standard built-in Object prototype Object.
The Function prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype Object.
Note: The internal conversion rules of Number. prototype. valueOf are slightly more complex than expected.

I have two questions.:

1. For ToObject, when the parameter is a Function object, it seems that no specific explanation is provided in the specification for how to process the returned object. Currently, we only rely on experiment speculation (or maybe I did not find it)
2. valueOf application scenarios, which have not been used by any brother in actual development
Last:

If there are any mistakes or omissions in this example, please point out. If you think the article is useful to you, click "recommended ":)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.