Consider how JavaScript's Date constructor creates an object that returns a default string when referenced directly:
var date = new Date();
document.write(date); // Outputs string: Mon May 23 2016 08:48:14 GMT-0400 (EDT)
// Expected output: [object Object]
document.write('<br/>', date.getFullYear()); // Can call methods as expected.
document.write('<br/>', date.toString());
According to MDN documentation:
If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
(emphasis mine)
The Date constructor returns an object, yet when that object is referenced directly, it returns a string representing the current date and time instead of a representation of the methods and properties as expected.
How can I achieve the same behavior with an object constructor of my own creation?
For example:
// My CoolObj constructor function
var CoolObj = function () {
var self = this;
var i = 0;
this.coolMethod = function () {
i += 1;
return self.coolProperty + ' and increment ' + i;
};
this.coolProperty = 'My cool string';
}
var myCoolObj = new CoolObj(); // Instantiate new object from constructor;
// Just like `var date = new Date();` above.
document.write(myCoolObj); // Outputs [object Object];
// I want to output a string, like Date does.
// For example: 'My cool direct-reference string.'
document.write('<br/>', myCoolObj.coolProperty); // Can call properties...
document.write('<br/>', myCoolObj.coolMethod()); // ...and methods as expected.
I'd like it to return a string of some kind when it is referenced directly, while providing the ability to call its methods and properties as normal.
UPDATE:
The linked question does provide the answer:
Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?
tl;dr: Define CoolObj.prototype.toString
which will get called by functions like console.log
and document.write
that attempt to cast objects to a string before output.
// My CoolObj constructor function
var CoolObj = function () {
var self = this;
var i = 0;
this.coolMethod = function () {
i += 1;
return self.coolProperty + ' and increment ' + i;
};
this.coolProperty = 'My cool string';
}
// Define a custom `toString` method on the constructor prototype
CoolObj.prototype.toString = function () {
return 'My cool direct-reference string.';
}
var myCoolObj = new CoolObj(); // Instantiate new object from constructor;
// Just like `var date = new Date();` above.
document.write(myCoolObj); // Outputs [object Object];
// I want to output a string, like Date does.
// For example: 'My cool direct-reference string.'
document.write('<br/>', myCoolObj.coolProperty); // Can call properties...
document.write('<br/>', myCoolObj.coolMethod()); // ...and methods as expected.