質問

I have a massive javascript file with many function expressions. All of a sudden console gives me the following errors:

In IE

The value of the property 'myFunc' is null or undefined, not a Function object

In Firefox

TypeError: myFunc is not a function

This is how I call the function:

myFunc();

This is the function:

myFunc = function() {
  //do stuff
}

This is happening on ALL function expressions. If I change one to a function declaration it works, but then will fail on some other function expression call inside of it. What the heck?

役に立ちましたか?

解決

Possibility 1

If you are calling the function expression before it is defined, you will get this error. If you however turn it into a function declaration, the function declaration would get hoisted to the top of the scope, and could be called before or after the actual declaration occurs. So:

functionFoo();
var functionFoo = function() {

};

Will give this error, because you are trying to call the function before it is defined. But:

functionFoo();
function functionFoo() {

}

Will work, because actual function declarations are hoisted to the top of the scope, and can be used anywhere.

Possibility 2

If you are calling the function expression from a different scope that is outside where the function expression is defined, you will get this error. function expressions, like other variables, can only be used within the scope they are defined. So:

$( document ).ready( function() {
   var functionFoo = function() {

   };
} );
functionFoo();

Will give you an error, because the defining of the function happens in a different scope than the call. But:

$( document ).ready( function() {
   var functionFoo = function() {

   };
   functionFoo();
} );

Will work just fine, because both the defining and the call happen in the same scope.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top