Understanding of tolocalestring(), tostring(), valueof()

Time:2021-7-25

JavaScript

toLocaleString()toString()valueOf()Is the method of an instance of the complex data type object of JavaScript.

toString()

Returns a string representing the object.

Each object has onetoString()Method is called automatically when the object is represented as a text value, or when an object is referenced as an expected string. By default,toString()Methods are used by eachObjectObject inheritance. If this method is not overridden in the custom object,toString()return  “[ objecttype]”, wheretypeIs the type of object. The following code illustrates this:

var o = new Object();
o.toString(); // returns [object Object]

toLocaleString()

toLocaleString()Method returns a string representation of the object. This method is used to overload derived objects for locale specific purposes.

This method actually returns the result of calling tostring().

Array.prototype.toLocaleString()

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });

console.log(localeString);
// expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary

valueOf()

Returns the original value of the specified object

JavaScript callvalueOfMethod converts the object to its original value. You rarely need to call it yourselfvalueOfmethod; JavaScript automatically calls an object with the original value to be expected when it is encountered.

By default,valueOfMethod byObjectEach subsequent object inherits. Each built-in core object overrides this method to return the appropriate value. If the object has no original value, thevalueOfThe object itself is returned.

Many built-in objects in JavaScript have rewritten this function to meet their own functional needs. Therefore, the return value and return value type of valueof () method of different types of objects may be different.

You can use it in your own codevalueOfConverts built-in objects to original values. When creating custom objects, you can overrideObject.prototype.valueOf()To call a custom method instead of the defaultObjectmethod.

function MyNumberType(n) {
    this.number = n;
}

MyNumberType.prototype.valueOf = function() {
    return this.number;
};

var myObj = new MyNumberType(4);
myObj + 3; // 7

Calling scenarios of tostring() and tostring()

These two methods are often called during type conversion.

Number()

Number () is used to convert other types into numeric types. One of its conversion rules is to call its valueof () method when converting an object. If the object itself is returned (like most array types, all function types, and custom objects without overriding valueof ()), then number () is used to convert, and the result must be Nan.

Then call its toString () method instead, if the return is similar to"[object type]", the result of number() is Nan.

function myObj(){}

myObj.prototype.valueOf = function(){
    return "1"
}

myObj.prototype.toString = function(){
    return "2"
}

var obj = new myObj();
Number(obj);       //1


//Then modify valueof () to return the object itself
myObj.prototype.valueOf = function(){ return this;}
obj.valueOf();        //myObj()
Number(obj);          //2

The above code defines toString () and valueof () for obj prototypes. It is also possible to directly define obj.

Additive operators

Additive operators include addition and subtraction

For addition, if one operand is an object, first call its tostring() to obtain the corresponding string value, and then splice it into a new string. If null or undefined is returned, the string () function is called and the strings “null” and “undefined” are obtained

var res = 1 + obj;


//Equivalent to
var res;
if(typeof obj.toString() === "string"){
    res = 1 + obj.toString(); 
}
else if([null,undefined].includes(typeof obj)){
    res = 1 + String(typeof obj);
}

For subtraction, if an operand is an object, its valueof () is called to obtain its value. If the obtained value is Nan, the result of subtraction is Nan. If the object does not have a valueof () method, call its toString () method to convert it to a string first, and then number () to a value.

Thanks for reading!

reference resources:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]