Is it possible to automatically stringify in JavaScript?

  • A+
Category:Languages

I know I can create a toString() function on an object, so that every time it's printed or treated like a string it will first stringify the object with that function.

Is it possible to do that directly so I can use String object functions on the object?

var SomeObject = function(a, b){     this.a = a;     this.b = b }  SomeObject.prototype.toString = function(){     return [ this.a, this.b ].join(' ') }  var objInstance = new SomeObject('this', 'that');  console.log(objInstance + '')                // This that console.log(("" + objInstance).split(''))    // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ] console.log(objInstance.split())             // Error 

Is it possible to do so that the object "behaves" like a string when a String function is called on it?

In other words, I'd like objInstance.split() to have the same result as ("" + objInstance).split(''), and also objInstance.length or objInstance.match(/something/), etc.

 


You can let your objects inherit from String so that all string methods become available:

class SomeObject extends String {   constructor(a, b) {     super(a + " " + b);     this.a = a;     this.b = b;   } }  var obj = new SomeObject('this', 'that'); console.log(obj.split(""));

No need to use complicated Proxy solutions :-)

All the String.prototype methods (except for .toString, .valueOf and [Symbol.iterator]) are "intentionally generic; [they do] not require that its this value be a String object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString() or .valueOf as usual).

You don't even need to use ES6 class extends to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:

function SomeObject(a, b) {   this.a = a;   this.b = b; } SomeObject.prototype = Object.create(String.prototype); SomeObject.prototype.constructor = SomeObject; SomeObject.prototype.toString = function() {     return this.a + " " + this.b; };  var obj = new SomeObject('this', 'that'); console.log(obj.split(""));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: