将方法/变量注入Javascript范围 [英] Injecting methods/variables into a Javascript scope
问题描述
我希望能够在文件开头使用我没有要求的方法()。
I want to be able to use methods that I haven't required() at the beginning of the file.
这样的事情:
var contact = require('contact');
person = contact.create({
'name': createName()
});
这里我想使用函数createName(),即使我没有明确地要求它() 。
Here I want to use the function createName() even if I haven't required() it explicitly.
以下是Ruby中的示例:
Here are examples in 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一样优雅和简单。
It doesn't have to be exactly like the example, but somehow inject methods/variables into the code without explicitly using require(), so it would be as elegant and simple as Ruby.
这可以在Javascript中使用吗?
Is this possible in Javascript?
推荐答案
编辑:可以只使用createName ()并且不需要导出它。但是您需要导出包含它的模块。
EDIT: It is possible to just use createName() and its not required to export it. But it is required for you to export the module that contains it.
示例:(test2.js)
Example: (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.
这篇关于将方法/变量注入Javascript范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!