Array类作为Node JS中的新模块

时间:2013-06-16 23:47:13

标签: javascript node.js module

我需要在Array类中添加一些原型,在我可以执行的本机javascript中

 var myArray = Array;
 myArray.prototype.myMethod = function(){}
 var testArray = new myArray();
 testArray.contains();

但现在我需要通过节点js模块和 exports myArray作为类来执行此操作,因此可以从中创建一些对象,我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果直接从模块中添加到Array原型,则主范围内的Array可以访问它

要查看此内容,请将以下行添加到foo.js

Array.prototype.foo = "bar";

然后启动repl并运行

$ node
> Array.prototype.foo
undefined // <-- Array normally doesn't have foo
> require('./foo')
{}
> Array.prototype.foo
'bar' // <-- note how it's defined now
> [].foo
'bar' // <-- as expected

您可以使用其他基本对象(例如Number

)执行相同的操作
相关问题