覆盖特定功能的toString

cle*_*ort 5 javascript overloading

在下面查看修改内容! 我目前正在寻找一种方法来重载动态生成(由函数返回)toString一个特定函数的方法。我知道我可以重载的toString功能Function.prototype,但这将重载所有 toString功能的所有功能,我想避免这种情况。

我的示例函数:

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())
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试将函数视为普通的JavaScript对象。

func.toString = function() {
    return this();
}
Run Code Online (Sandbox Code Playgroud)

这导致Function.prototype.toString仍然调用而不是func.toString

func.prototype无法尝试访问,该prototype属性未定义,因为它是一个函数而不是对象。不能选择覆盖toStringFunction.prototype也不能更改func为对象,因为这可能会破坏与代码较早部分的兼容性。

编辑:上面所做的尝试显然不起作用,因为我正在覆盖toString函数的,func而不是toString返回函数的。现在有一个更好的问题:是否有一种优雅的方法来覆盖toString所有返回的函数,func以便它们“共享”相同的toString。(意味着我不必toString为每个返回的函数都指定。)

Bra*_*dan 3

您可以通过在返回之前将其存储在变量中来定义toString返回的函数:callme

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'
Run Code Online (Sandbox Code Playgroud)