将方法/变量注入Javascript范围

我希望能够在文件开头使用我没有要求的方法()。

像这样的东西:

var contact = require('contact'); person = contact.create({ 'name': createName() }); 

在这里我想使用函数createName(),即使我没有明确地要求它()。

以下是Ruby中的示例:

 # By extending a class it gets the class methods from the parent: class Section < ActiveRecord::Base belongs_to :document has_many :paragraphs end # By using a block and executing it in an object containing those methods used namespace "admin" do resources :posts, :comments end 

它不一定非常类似于示例,但不知何故在没有显式使用require()的情况下将方法/变量注入到代码中,因此它将像Ruby一样优雅和简单。

这可能在Javascript中吗?

编辑 :可以只使用createName(),而不需要导出它。 但是您需要导出包含它的模块。

示例:(test2.js)

 exports.normal = function() { console.log("Exporting is normal"); }; GLOBAL.superior = function() { console.log("Global is superior"); }; var privateInferior = function() { console.log("Private is inferior") } var i_am_a_variable = 5; var i_m_an_array = [1, 2, 3, 4, 5]; 

(test1.js)

 var test2 = require('./test2.js'); test2.normal(); // works!! superior(); // works!! privateInferior(); // does not work as it is not global. console.log(i_am_a_variable); // does not work as it is not global. console.log(i_m_an_array); // does not work as it is not global. normal() // does not work as it is exported. Available only via test2. 

如果createNamecontact定义如此

 exports.createName = func; 

然后你可以使用with “导出”它(以及所有其他类似定义的函数/属性)

 with (require('contact')) { var name = createName(); } 

这在function上与…相同

 var contact = require('contact'); var name = contact.createName(); 

只需根据传递给它的对象创建一个新的范围。 由于require只返回一个对象,因此可以与其一起with来模拟某些其他语言的命名空间/函数导入function。 只记得用花括号包装所有东西。