[英]RequireJS: Define a module - TypeError: Unable to get property of undefined or null reference
I have two JavaScript files file1.js
and file2.js
which I want to create modules out of it to use it with RequireJS. 我有两个JavaScript文件
file1.js
和file2.js
,我想从中创建模块以将其与RequireJS一起使用。
file1.js file1.js
define('file1', ['file2'], function(myVar) {
console.log(myVar);
myVar.doSomething = function() {
return {
'test': 13
}
}
});
As you can see, there is a dependency to file2.js
and I need to get the myVar
. 如您所见,存在对
file2.js
的依赖关系,我需要获取myVar
。 Here you can see file2
and a code snippet what I am doing inside this file. 在这里,您可以看到
file2
和一个代码片段,我在该文件中正在做什么。
file2.js file2.js
define('file2', ['someOtherDep'], function(someVarFromSomeOtherDep) {
var myVar = (function() {
var test = someVarFromSomeOtherDep.test.a;
var doIt = function(var1) {
// …
return x;
};
return {
doIt: doIt
}
}());
console.log(myVar);
return myVar;
});
If I use file1
as a dependency and call myVar.doSomething()
, I get TypeError: Unable to get property 'doSomething' of undefined or null reference
and both console.log
shows [object Object] {}
. 如果我使用
file1
作为依赖项并调用myVar.doSomething()
, myVar.doSomething()
得到TypeError: Unable to get property 'doSomething' of undefined or null reference
并且两个console.log
显示[object Object] {}
。
Here is the file which depends on file1
: 这是取决于
file1
:
define(['file1'], function(myVar) {
var test = myVar.doSomething();
});
So, what's wrong here? 那么,这怎么了? It seems that
myVar
is not returned correctly from file2
? 似乎
myVar
没有从file2
正确返回?
both console.log shows
[object Object] {}
两个console.log都显示
[object Object] {}
That's odd. 真奇怪 Have you tried expanding the view?
您是否尝试过扩大视野? You should be able to see your methods.
您应该能够看到您的方法。
I get
TypeError: Unable to get property 'doSomething' of undefined or null reference
So, what's wrong here?我收到
TypeError: Unable to get property 'doSomething' of undefined or null reference
那么,这是怎么回事? It seems that myVar is not returned correctly from file2?似乎myVar没有从file2中正确返回?
No. myVar
is not returned correctly from file1 - in fact, nothing is returned there at all! 第
myVar
不是从文件1返回正确的-事实上,返回什么都没有了!
define('file1', ['file2'], function(myVar) {
console.log(myVar);
myVar.doSomething = function() {
return {
'test': 13
}
}
return myVar;
// ^^^^^^^^^^^^^
});
You're getting the error from the line var test = myVar.doSomething();
您从
var test = myVar.doSomething();
行得到了错误var test = myVar.doSomething();
(that depends on file 1), not from file 1 (that depends on file 2). (取决于文件1),而不是来自文件1(取决于文件2)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.