简体   繁体   English

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

[英]Node.js util.format() as String.prototype

I am trying to create/extend the node.js util.format function so that it can be used as a prototype (eg: "Hello %s".format("World")). 我正在尝试创建/扩展node.js util.format函数,以便可以将其用作原型(例如:“ Hello%s” .format(“ World”))。 However, I have been unsuccessful trying it. 但是,我尝试失败。 I have tried the following formats to no avail: 我尝试了以下格式无济于事:

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

and

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

and also 并且

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

None of these work. 这些都不起作用。 Do you have any idea what I am doing wrong? 你知道我在做什么错吗?

Thanks, Manuel 谢谢,曼努埃尔

I assume you would be calling it like this? 我想您会这样称呼它?

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

like this: 像这样:

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

In your first example, you are only passing 2 arguments, the format string, and the arguments object. 在第一个示例中,您仅传递了2个参数,格式字符串和arguments对象。 You get closer with your second attempt, but the context of format should probably be util . 您可以进行第二次尝试,但可以更加接近,但是format的上下文可能应该是util You need to add this to the set of arguments applied to format . 您需要this添加到应用于format的参数集中。 Also when working with this on a string, you are working with the string Object, not the string literal, so you must get the literal version using valueOf . 也有工作时, this在一根绳子上,您正在使用String对象的工作,而不是字符串文字,所以你必须使用得到的文字版本valueOf

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

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