问题
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