Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

jquery - Javascript function cannot be found

I have the following code in document.ready()

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

    setMinContentHeight();

    function setMinContentHeight() {

        // removed for clarity
    }
}

I simply check if the page is correct (#site-master), then call my minimum height function, however I'm getting the following error in firebug: ReferenceError: setMinContentHeight is not defined.

I'm no javascript expert, but how can this be? The function works if I move it outside of document.ready(). I have checked and the code inside the if statement is reached.

Also, is this the best way of achieving what I want?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...