Node.js util.format() as String.prototype



我正在尝试创建/扩展node.js util。format函数,以便它可以用作原型(例如:"Hello %s".format("World"))。然而,我一直没有成功。我尝试了以下格式,但没有效果:

String.prototype.format = function(){return util.format(this, arguments)};

String.prototype.format = function(){return util.format.apply(this, arguments)};

String.prototype.format = function(args){return util.format(this, args)};

这些都不起作用。你知道我做错了什么吗?

谢谢,Manuel

我想你会这样称呼它?

"%s: %s".format('key', 'val');

:

String.prototype.format = function(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift(this.valueOf());
  return util.format.apply(util, args);
};

在你的第一个例子中,你只传递了2个参数,格式字符串和参数对象。在第二次尝试时,您会更接近于此,但格式的上下文可能应该是util。您需要将this添加到应用于format的参数集合中。此外,当在字符串上使用this时,您正在使用字符串对象,而不是字符串文字,因此您必须使用valueOf获得文字版本。

最新更新