Javascript typeof Typeahead returns undefined

我的梦境 提交于 2020-01-25 10:53:05

问题


I'm loading the bootstrap Typeahead plugin prior to calling Typeahead in my script, but typeof Typeahead return undefined even when it's absolutely loaded.

Javascript file line 2650:

!function($){"use strict";var Typeahead=function(element,options) // ... rest of plugin

Javascript file line 2765:

alert(typeof Typeahead);

alerts undefined

why would this be the case?


回答1:


You don't really show us enough of the code. But, if the:

alert(typeof Typeahead);

is outside of the function block where var Typeahead = function() {...} appears, then you are outside the scope where that variable (and thus function) is defined so the variable will be undefined. Variables are only visible within the scope in which they are defined.

If you want var Typeahead to be available outside that function block, then it must be declared at a higher scope.

As an example:

function foo() {
   // define local variable only visible within function foo
   var greeting = "Hi";
}

console.log(typeof greeting);   // will show "undefined"

// define higher scope variable visible in foo and outside of foo
var greeting = "Hi";

function foo() {
    console.log(greeting);      // will show "Hi"
}

console.log(greeting);          // will show "Hi"


来源:https://stackoverflow.com/questions/29112472/javascript-typeof-typeahead-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!