TypeScript扩展模块中的对象 [英] TypeScript extend object in module

查看:279
本文介绍了TypeScript扩展模块中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的事情实际上与 this

What I want to do is really similar to this and this except I'm trying to figure out how to put an ArrayExtension inside a module.

我正在尝试获得与C#扩展方法工作方式类似的方式,那样我就可以导入模块,并获得额外的方法.我提供的链接显示了如何扩展现有对象,但是我还无法弄清楚如何将其封装到模块中.

I'm trying to get something similar to the way C# extension methods work, that way I can just import the module and I'll have my extra methods. The links I provided show how to extend an existing object, but I haven't been able to figure out how to encapsulate that into a module.

推荐答案

如果您要针对非浏览器环境(例如node.js),则可以实现此操作,因为您将能够将引用传递给模块的全局成员,例如Array,转到其他模块.然后,这些其他模块可以使用额外的功能扩展传入的对象和/或其原型,这些功能只能由调用模块访问.为了获得这些扩展,其他模块也必须这样做.因此,由于导入是显式的,因此将冲突最小化.

If you're targeting non-browser environments like node.js this will be possible because you will be able to pass references to your module's global members, such as Array, to other modules. Those other modules can then extend the passed in object and/or its prototype with extra functionality which will be only accessible by the calling module. Other modules would have to do the same in order to get these extensions; therefore, conflicts are minimized since imports are explicit.

但是,在浏览器环境中并非如此,因为只有一个window对象,并且其成员的任何更改都随处可用.一旦您的任何模块扩展了Array,这些扩展将可用于所有其他模块-增加了发生冲突的可能性,并使代码难以推理.

However, in browser environments this is not the case since there is only one window object and any changes to its members are available everywhere. As soon as any of your modules extended Array those extensions would be available to all other modules -- increasing the possibility for conflicts and making the code harder to reason about.

话虽如此,但JS中有模式,因此有TypeScript,它们可以完成您想要的操作.一种这样的模式是'mixin'模式,它允许您基于对象实例添加其他功能.您可以将可重复使用的代码分成混合模块,然后在需要时将其应用于对象,甚至可以在构造函数中自动应用于对象.来看一下它,以获得不错的概述和实现示例:

With that said, there are patterns in JS, and therefore TypeScript, which should accomplish what you want. One such pattern is the 'mixin' pattern which allows you to add on extra functionality on an object instance basis. You could separate re-usable code into mixin modules which could then be applied to an object when needed, or even automatically in constructors. Take a look at this for a decent overview and implementation examples: http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

这篇关于TypeScript扩展模块中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆