我想将一些方法添加到express.js(咖啡脚本)的通用类型(如字符串,整数等)中。 我在节点上是全新的。 我只想这样做:
"Hi all !".permalink().myMethod(some).myMethod2();
5.doSomething();
variable.doSomethingElse();
这个怎么做 ?
您可以使用以下方法向String原型添加方法:
String::permaLink = ->
"http://somebaseurl/archive/#{@}"
String::permalink
是String.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'