Overwrite toString for a specific function

Check out the edits below! I'm currently looking for a way to overload the toString method of one specific function that is generated dynamically (returned by the function). I know that I can overload the toString Function.prototype , but this will overload all toString functions of all functions, I want to avoid this.

My sample function:

 var obj = { callme: function() { return function() { // Dynamically fetch correct string from translations map return "call me, maybe"; } } } // Binding callme to func, allowing easier access var func = obj.callme.bind(obj); console.log(func, func()) 

So far, I have been trying to just treat a function as a regular JavaScript object.

 func.toString = function() { return this(); } 

This causes Function.prototype.toString still be called instead of func.toString .

Attempting to access func.prototype not possible, the prototype property is undefined, because it is a function, not an object. Overwriting toString of Function.prototype not an option; changing a func object to an object is also not possible, since it can slow down compatibility with old parts of the code.

Edit: The attempts made above obviously do not work, as I am overwriting the toString the func function, not the toString returned function. Now the best question is: is there an elegant way to overwrite toString all functions returned by func so that they "share" the same toString . (So ​​I do not need to specify toString for each function returned.)

+4
source share
2 answers

You can define toString in the returned function in callme by storing it in a variable before returning it:

 var obj = { callme: function (){ function toString(){ return this(); } var f = function (){ // Dynamically fetch correct string from translations map return "call me, maybe"; }; f.toString = toString; return f; } }; var func = obj.callme.bind(obj); console.log(func); //=> [Function] console.log(func()); //=> { [Function] toString: [Function: toString] } console.log(func().toString()); //=> 'call me, maybe' 
+2
source

If you want a custom value, you could not just write a method for it instead of overwriting the toString prototype.

Otherwise, if you need to change it to everything, you can do something like:

 String.prototype.toString = function() {return this+"test";} 
0
source

Source: https://habr.com/ru/post/1442306/


All Articles