这是我对 requirejs 的第一次修补,我认为我对它有很好的处理能力,除了:为什么模块中定义的函数无法访问 require() 内的局部变量以及我如何才能使用它?实现这个目标吗?
如果我们能够专注于这个问题,而不是我使用 eval()、更好或替代的方法来定义 test() 的事实,或者可能存在的拼写错误,我们将不胜感激。下面的代码。
在全局命名空间中给出以下代码:
require(["test"], function(testModule) {
var test1 = testModule.test1;// same as local test()
var test2 = testModule.test2; // modified to work as module
//local function same as testModule.test1
function test (name, test){
return test+'='+eval(name+test);
}
//define class & instance for testing
var MyClass1 = function (name) {
this.name = name;
};
var mc1 = new MyClass1('instance 1');
var objName = 'mc1'
test(objName, '.name'); // works as expected
test1(objName, '.name'); // error: mc1 is not defined
test1.call(this, objName, '.name'); // error: mc1 is not defined
test2(mc1, objName+'.name'); // works as expected
})
和测试模块定义:
define({
test1: function (name, test){
return test+'='+eval(name+test);
},
test2: function (obj, test){
var parts = test.split('.');
parts[0] = 'obj';
test = parts.join('.');
return test+'='+eval(test);
}
});
问题:
a) 部分 当我调用 test1(objName, '.name') 时,为什么它看不到定义为 var mc1 = new MyClass1('instance 1') 的局部变量?
我知道这是有充分理由的,与保持全局命名空间清洁有关,我只是不明白它怎么看不到它。 Define() 的 this 与 require() 的 this 指向相同的命名空间。
b) 部分如果我想让测试模块访问 var mc1,我该怎么做?
最佳答案
When i call test1(objName, '.name'), why does it not see the local variable defined as var mc1 = new MyClass1('instance 1')?
它们在不同的函数中定义。这与行不通的原因相同:
function a() {
var hello = 'world'
b()
}
function b() {
alert(hello)
}
<小时/>
If i wanted to give the test module access to var mc1 how could i go about doing so?
将定义更改为:
test1: function (name, test, mc1){ ... }
并显式传递 mc1 变量:
test1(objName, '.name', mc1)
这与 require.js 无关,这就是 javascript 的工作原理。
关于javascript - requirejs:为什么模块中定义的函数无法访问 require() 内的局部变量,我该如何实现这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260674/