[英]Access enumeration member of an object in JavaScript
I'm trying to pass an "Options"-Object to the constructor of another object. 我正在尝试将“选项”对象传递给另一个对象的构造函数。 Options have enumerations which I try to read in another file.
选项具有枚举,我尝试读取另一个文件。
js/mainApp.js: JS / mainApp.js:
square = new World(20, 20, null, 0);
var opts = new Options(MODE.SINGLE, REGION.MIDDLE_EAST);
world = new World(0, 0, "img/whatever.png", opts);
js/options.js : js / options.js:
var MODE = {
SINGLE : 1,
MULTI : 2
};
var REGION = {
MIDDLE_EAST : { xTranslate : -2300, yTranslate: -700, scale : 1.2}
};
function Options(MODE, REGION) {
this.mode = MODE;
this.region = REGION;
}
Now in the World constructor I'm getting the error " opts.region is undefined
" for the second alert. 现在在World构造函数中,第二个警报出现错误“
opts.region is undefined
”。 For some reason the first alert shows the expected " { xTranslate : -2300, yTranslate: -700, scale : 1.2}
" 由于某种原因,第一个警报显示了预期的“
{ xTranslate : -2300, yTranslate: -700, scale : 1.2}
”
js/options.js: JS / options.js:
var World = ExtendingSomething.extend(
{
initialize: function(x, y, imageURL, opts) {
alert (JSON.stringify(opts.region));
alert (JSON.stringify(opts.region.scale));
...
}
}
);
Edit: I added few information 编辑:我添加了一些信息
I don't understand why I'm getting this error is undefined
while it works in in this jsfiddle (thanks for creating to Thomas CG de Vilhena). 我不明白为什么我得到这个错误
is undefined
,而它的工作原理在这个的jsfiddle (感谢创造托马斯·CG德维赫纳)。
Maybe it's a problem that I'm using different files? 使用不同的文件可能是个问题吗? still: Why is there no problem with the call
opts.region
, but as soon as I'm calling opts.region.scale
the error opts.region is undefined
appears(not opts.region.scale!). still:为什么调用
opts.region
没问题,但是一旦我调用opts.region.scale
,错误opts.region is undefined
出现opts.region is undefined
(不是opts.region.scale!)。
<script type="text/javascript" src="js/mainApp.js"></script>
<script type="text/javascript" src="js/options.js"></script>
<script type="text/javascript" src="js/world.js"></script>
Edit: I needed to add another line of code to understand the problem 编辑:我需要添加另一行代码以了解问题
The problem is the constructor call with wrong parameters. 问题在于参数错误的构造函数调用。 There should be some kind of type check, otherwise it gives a TypeError.
应该进行某种类型检查,否则会给出TypeError。
remove any wrong call to constructor or add a check 删除对构造函数的任何错误调用或添加检查
square = new World(20, 20, null, 0);
Script files should be loaded in below order. 脚本文件应按以下顺序加载。
<script type="text/javascript" src="js/options.js"></script>
<script type="text/javascript" src="js/world.js"></script>
<script type="text/javascript" src="js/mainApp.js"></script>
It seems we are using objects even before they are being loaded. 似乎我们甚至在加载对象之前就使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.