【发布时间】:2012-04-07 04:17:50
【问题描述】:
看起来“$smth 不是函数”是 JavaScript 的一个非常常见的问题,但是在查看了很多线程后,我仍然无法理解是什么导致了我的情况。
我有一个自定义对象,定义为:
function Scorm_API_12() {
var Initialized = false;
function LMSInitialize(param) {
errorCode = "0";
if (param == "") {
if (!Initialized) {
Initialized = true;
errorCode = "0";
return "true";
} else {
errorCode = "101";
}
} else {
errorCode = "201";
}
return "false";
}
// some more functions, omitted.
}
var API = new Scorm_API_12();
然后在另一个脚本中,我尝试通过以下方式使用此 API:
var API = null;
function ScormProcessInitialize(){
var result;
API = getAPI();
if (API == null){
alert("ERROR - Could not establish a connection with the API.");
return;
}
// and here the dreaded error pops up
result = API.LMSInitialize("");
// more code, omitted
initialized = true;
}
getAPI() 的东西,看起来像这样:
var findAPITries = 0;
function findAPI(win)
{
// Check to see if the window (win) contains the API
// if the window (win) does not contain the API and
// the window (win) has a parent window and the parent window
// is not the same as the window (win)
while ( (win.API == null) &&
(win.parent != null) &&
(win.parent != win) )
{
// increment the number of findAPITries
findAPITries++;
// Note: 7 is an arbitrary number, but should be more than sufficient
if (findAPITries > 7)
{
alert("Error finding API -- too deeply nested.");
return null;
}
// set the variable that represents the window being
// being searched to be the parent of the current window
// then search for the API again
win = win.parent;
}
return win.API;
}
function getAPI()
{
// start by looking for the API in the current window
var theAPI = findAPI(window);
// if the API is null (could not be found in the current window)
// and the current window has an opener window
if ( (theAPI == null) &&
(window.opener != null) &&
(typeof(window.opener) != "undefined") )
{
// try to find the API in the current window�s opener
theAPI = findAPI(window.opener);
}
// if the API has not been found
if (theAPI == null)
{
// Alert the user that the API Adapter could not be found
alert("Unable to find an API adapter");
}
return theAPI;
}
现在,可能找到了 API,因为我没有收到“无法找到...”消息,代码继续尝试初始化它。但是firebug告诉我API.LMSInitialize is not a function,如果我尝试用alert(Object.getOwnPropertyNames(API));调试它,它会给我一个空白警报。
我错过了什么?
【问题讨论】:
-
在
API = getAPI();之后执行console.log(API)会得到什么? -
请你告诉我你想在初始化后做什么..
-
我得到了那个错误,因为我有一个循环依赖。也许这会对其他人有所帮助。
标签: javascript javascript-objects