toString() and valueOf()

Keywords: Web Development Javascript

1. toString()

The toString() method returns a string representing the object. Each object has a toString() method that is automatically invoked when the object is represented as a text value, or when an object is referenced in the expected string format. By default, the toString() method is inherited by each Object object. If this method is not overwritten in the custom object, toString() returns "[object type]", where type is the object type.

Example:

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

You can customize a method to replace the default toString() method. The toString() method cannot pass in parameters and must return a string. The custom toString() method can be any value we need, but it will become very useful if it comes with information about the object.

Example:

function Dog(name,breed,color,sex) {
   this.name=name;
   this.breed=breed;
   this.color=color;
   this.sex=sex;
}

var theDog = new Dog("Gabby","Lab","chocolate","female");

The inherited toString() method:

theDog.toString(); // returns [object Object]

Override default toString():

Dog.prototype.toString = function dogToString() {
  var ret = "Dog " + this.name + " is a " + this.sex + " " + this.color + " " + this.breed;
  return ret;
}

Call custom toString():

theDog.toString(); // "Dog Gabby is a female chocolate Lab"

You can get the type of each object by toString(). In order for each object to be detected by Object.prototype.toString(), it needs to be called in the form of Function.prototype.call() or Function.prototype.apply(), passing the object to be checked as the first parameter, called thisArg.

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

2. valueOf()

The valueOf() method returns the original value of the specified object.

JavaScript calls the valueOf method to convert an object to its original value. You rarely need to call the valueOf method yourself; JavaScript calls it automatically when you encounter an object with the expected original value.

By default, the valueOf method is Object Each subsequent object inherits. Each built-in core object overrides this method to return the appropriate value. If the object has no original value, valueOf returns the object itself.

Many built-in objects in JavaScript have rewritten this function to make it more suitable for their own functional needs. Therefore, the return value and return value type of the valueOf() method for different types of objects may be different.

Example:

/ Array: Returns the array object itself
var array = ["ABC", true, 12, -5];
console.log(array.valueOf() === array);   // true

// Date: The current time is milliseconds from midnight on January 1, 1970
var date = new Date(2013, 7, 18, 23, 11, 59, 230);
console.log(date.valueOf());   // 1376838719230

// Number: Returns a numeric value
var num =  15.26540;
console.log(num.valueOf());   // 15.2654
var a = new Number('a');
console.log(a.valueOf()); //NaN


// Boolean: Returns a Boolean value true or false
var bool = true;
console.log(bool.valueOf() === bool);   // true

// new a Boolean object
var newBool = new Boolean(true);
// valueOf() returns true, with the same value.
console.log(newBool.valueOf() == newBool);   // true
// But they are not equal. The two types are different. The former is boolean type, and the latter is object type.
console.log(newBool.valueOf() === newBool);   // false
var newBool = new Boolean('string');
console.log(newBool.valueOf()); // true


// Function: Returns the function itself
function foo(){}
console.log( foo.valueOf() === foo );   // true
var foo2 =  new Function("x", "y", "return x + y;");
console.log( foo2.valueOf() );
/*
ƒ anonymous(x,y
) {
return x + y;
}
*/

// Object: Returns the object itself
var obj = {name: "Zhang San", age: 18};
console.log( obj.valueOf() === obj );   // true

// String: Returns string values
var str = "http://www.xyz.com";
console.log( str.valueOf() === str );   // true

// new a string object
var str2 = new String("http://www.xyz.com");
// The values of the two are equal, but not equal, because of the different types, the former is string type and the latter is object type.
console.log( str2.valueOf() === str2 );   // false

You can use valueOf to convert built-in objects into original values in your code. When creating a custom object, you can override Object.prototype.valueOf() to invoke a custom method instead of the default Object Method.

Example:

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

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

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

valueOf() has higher priority than toString();

 

Posted by agoe on Sun, 20 Jan 2019 09:57:12 -0800