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

问题描述 投票:1回答:2

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

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

这个怎么做 ?

coffeescript
2个回答
5
投票

您可以使用以下方法向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。


0
投票

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

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

'hello, world'
© www.soinside.com 2019 - 2024. All rights reserved.