When creating a x = new Date()
object, if you put it into console.log(x)
a string will be output.
Is there a way to make a custom object that w
Basically two methods returns values, which are not the object itself.
Object#toString
Every object has a
toString()
method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended fromObject
. If this method is not overridden in a custom object, `toString() returns "[object type]", where type is the object type.
Object#valueOf
JavaScript calls the
valueOf
method to convert an object to a primitive value. You rarely need to invoke thevalueOf
method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.By default, the
valueOf
method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value. If an object has no primitive value,valueOf
returns the object itself.You can use valueOf within your own code to convert a built-in object into a primitive value. When you create a custom object, you can override
Object.prototype.valueOf()
to call a custom method instead of the defaultObject
method.
To break it down for your question, you can implement both methods to a custom function.
When both methods are implemented and return primitive values, the valueOf
is called first. If valueOf
returns an object, toString
method is called.
You might have a look to this article: Fake operator overloading in JavaScript
function Custom(value) {
this.value = value;
}
Custom.prototype.valueOf = function () {
console.log('valueOf');
return this.value * 5;
};
var custom = new Custom(7);
console.log('' + custom); // no toString
Custom.prototype.toString = function () {
console.log('toString');
return this.value * 3;
};
Custom.prototype.valueOf = function () {
console.log('valueOf');
return {};
};
console.log('' + custom);