繁体   English   中英

Node.js util.format()作为String.prototype

[英]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)};

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

谢谢,曼努埃尔

我想您会这样称呼它?

"%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个参数,格式字符串和arguments对象。 您可以进行第二次尝试,但可以更加接近,但是format的上下文可能应该是util 您需要this添加到应用于format的参数集中。 也有工作时, this在一根绳子上,您正在使用String对象的工作,而不是字符串文字,所以你必须使用得到的文字版本valueOf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM