[英]How do I write extension methods that can be used globally in my Node.JS application?
Take for example this "StartsWith" extension: 以这个“ StartsWith”扩展为例:
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
If I was writing a web app, I would stick that code in an ExtensionMethods.js
page that I imported on a web page within my site. 如果我正在编写Web应用程序,则应将该代码粘贴到我在站点内的网页上导入的ExtensionMethods.js
页面中。
But what about the case of using this on the server with Node.js? 但是,如何在带有Node.js的服务器上使用它呢?
Thanks! 谢谢!
Since String
is globally available, it can be placed in any file that gets required. 由于String
是全局可用的,因此可以将其放在需要的任何文件中。 When a file gets required, it gets executed. 需要文件时,将执行该文件。
You don't even need to export anything. 您甚至不需要导出任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.