这个问题在这里已有答案:
我已经查看并找到了很多关于这个主题的解决方案 - 但是没有一个能够在我的具体实现中工作(我可以理解)。我是javascript(和web开发人员)的新手 - 所以我们可以从那开始。我想要做的是以下内容:
我的问题是我在变量(objName)中有对象名称(除法) - 我找不到通过使用objName实际引用对象内任何东西的方法。我找到了一些具体的答案 - 但我似乎无法在这种情况下开展工作。我认为这一切都与找到通过变量名称在窗口级别引用对象的正确方法有关。
这是我的代码(缩写为可读性)
文件:division.js
var division = {
name: "Bobby",
maintenanceForm : function() {
console.log('maint form');
}
}
HTML PAGE:
<head>
// Some other stuff in here too...
<script type="text/javascript" src="/objects/division.js"></script>
</head>
<body>
// Some divs/forms/etc
</body>
<script>
var objName = location.search.substr(1);
var objFile = "/objects/" + objName + ".js";
var scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.src = objFile;
scriptTag.addEventListener("load",objloaded);
document.head.appendChild(scriptTag);
function objloaded() {
console.log(objName); // prints our "division" so I know we have the value here.
console.log(division); // THIS WORKS
console.log(this[objName]) // This comes back undefined which makes sense
// because "this" is this function and not the
// global page scope.
// So how do I reference the object in
// the window scope through objName?
}
这是控制台日志:
我认为窗口[objName]会起作用。