Skip to content Skip to sidebar Skip to footer

Javascript Function Cannot Be Found

I have the following code in document.ready() if ($('#site-master').length > 0) { setMinContentHeight(); function setMinContentHeight() { // removed for clari

Solution 1:

Never declare your functions inside if or for statements:

function setMinContentHeight() {
    // removed for clarity
}

if ($("#site-master").length > 0) {
    setMinContentHeight();
}

If we address the ECMAScript specification, according to Chapter 12, if clause is considered to be a Statement (as well as for, while, with, try/catch, etc).

Hence, following the NOTE from Semantics section:

Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

It means that we cannot guarantee the consistent behavior in such cases, and, as a result, we will always get exception in strict mode in case if function was declared inside the statement.

Solution 2:

First, read on the difference between var functionName = function() {} and function functionName() {} to understand function declarations vs expressions. Now what do you have? Nothing of the two, since function declarations need to be on the top level of function/script code - nesting them in blocks is not allowed. It's called a function statement, is nonstandard and working differently.

Put it outside the if-block:

// here
if ($("#site-master").length > 0) {
    setMinContentHeight();
}
// or here:
function setMinContentHeight() {
    …
}

Solution 3:

if ($("#site-master").length > 0) {
    setMinContentHeight();
}
function setMinContentHeight() {
        // removed for clarity
}

You need to declare your function in the global scope.

Solution 4:

Place the call after you've defined the function and don't define functions inside an if block:

function setMinContentHeight() {
    // removed for clarity
}

if ($("#site-master").length > 0) {
    setMinContentHeight();
}

Solution 5:

Maybe you have problems with browser compatibility, but it works like this:

right:

n();
function n(){ alert('1'); }

wrong:

n();
var n = function(){ alert('1'); }

Post a Comment for "Javascript Function Cannot Be Found"