将方法添加到node.js express.js coffeescript中的字符串类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将方法添加到node.js express.js coffeescript中的字符串类相关的知识,希望对你有一定的参考价值。

我想将一些方法添加到express.js(咖啡脚本)的通用类型(如字符串,整数等)中。 我在节点上是全新的。 我只想这样做:

"Hi all !".permalink().myMethod(some).myMethod2();
5.doSomething();
variable.doSomethingElse();

这个怎么做 ?

答案

您可以使用以下方法向String原型添加方法:

String::permaLink = ->
   "http://somebaseurl/archive/#{@}"

String::permalinkString.prototype.permaLink简写

然后,您可以执行以下操作:

somePermalink = "some-post".permaLink()
console.log somePermalink.toUpperCase()

这将调用“ String.prototype.permaLink”函数,并将“ this”设置为“ some-post”字符串。 然后,permaLink函数创建一个新字符串,该字符串值的末尾包括“ this”(在Coffeescript中为@ )。 Coffeescript自动返回函数中最后一个表达式的值,因此permaLink的返回值是新创建的字符串。

然后,您可以在字符串上执行任何其他方法,包括使用上述技术定义​​的其他方法。 在此示例中,我调用了内置的String方法toUpperCase。

另一答案

您可以使用原型通过新函数扩展String或int对象

String.prototype.myfunc= function () {
  return this.replace(/^s+|s+$/g, "");
};
var mystring = "       hello, world        ";
mystring.myfunc();

'hello, world'

以上是关于将方法添加到node.js express.js coffeescript中的字符串类的主要内容,如果未能解决你的问题,请参考以下文章