Man*_*Bey 1 javascript node.js
我正在尝试创建/扩展node.js util.format函数,以便它可以用作原型(例如:"Hello%s".format("World")).但是,我尝试它是不成功的.我尝试了以下格式无济于事:
String.prototype.format = function(){return util.format(this, arguments)};
Run Code Online (Sandbox Code Playgroud)
和
String.prototype.format = function(){return util.format.apply(this, arguments)};
Run Code Online (Sandbox Code Playgroud)
并且
String.prototype.format = function(args){return util.format(this, args)};
Run Code Online (Sandbox Code Playgroud)
这些都不起作用.你知道我做错了什么吗?
谢谢,曼努埃尔
我猜你会这样称呼它?
"%s: %s".format('key', 'val');
Run Code Online (Sandbox Code Playgroud)
像这样:
String.prototype.format = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(this.valueOf());
return util.format.apply(util, args);
};
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,您只传递了2个参数,格式字符串和arguments对象.第二次尝试越接近,但格式的上下文可能应该是util.您需要添加this应用于的参数集format.当使用this字符串时,您正在使用字符串Object,而不是字符串文字,因此您必须使用字面值valueOf.