看下面的编辑!
我目前正在寻找一种方法来重载一个动态生成的特定函数(由函数返回)的toString
方法。我知道我可以重载 Function.prototype
的 toString
函数,但这会重载 all toString
函数 < em>all 函数,我想避免这种情况。
我的示例函数:
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())
到目前为止,我一直尝试将函数视为常规 JavaScript 对象。
func.toString = function() {
return this();
}
这导致 Function.prototype.toString
仍然被调用而不是 func.toString
。
尝试访问 func.prototype
是不可能的,prototype
属性是未定义的,因为它是一个函数而不是一个对象。
覆盖 Function.prototype
的 toString
不是一个选项,将 func
更改为对象也是不可能的,因为它可能会破坏与旧部分的兼容性代码。
编辑: 上面所做的尝试显然不起作用,因为我正在覆盖函数 func
的 toString
而不是 返回函数的 toString
。现在一个更好的问题:是否有一种优雅的方法来覆盖 func
返回的所有函数的 toString
,以便它们“共享”相同的 toString
。
(意味着我不必为每个返回的函数指定 toString
。)
最佳答案
您可以在 callme
中的返回函数上定义 toString
,方法是在返回之前将其存储在变量中:
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'
关于javascript - 为特定功能覆盖 toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087322/