在调用之前是否必须定义Javascript函数? [英] Does a Javascript function have to be defined before calling it?

查看:93
本文介绍了在调用之前是否必须定义Javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在定义它之前运行下面的函数,我将收到此错误...

If I run the function below before defining it, I will get this error...

Uncaught ReferenceError: openModal is not defined

运行然后定义

$(document).ready( function() {

    delay(openModal, 2000);

    delay = function (f, t) {
        setTimeout(function() {
            f();
        }, t);
    };

    openModal = function () {
        $('#modal-box').css( {
            left: $(window).width() / 2 - $('#modal-box').width() / 2,
            top: $(window).height() / 2 - $('#modal-box').height() / 2
        } );
        $('#modal-box').show();
        $('#modal-mask').show();
    };  

});

现在,如果我首先定义函数然后调用它就可以了...我有一个背景知识PHP所以我习惯能够全局访问函数,我做错了什么或者必须先定义所有函数才能使用它们?

Now if I define the function first and then call it it works...I have a background in PHP so I am used to being able to access functions globally, am I doing something wrong or do all functions have to be defined before they can be used?

$(document).ready( function() {

    delay = function (f, t) {
        setTimeout(function() {
            f();
        }, t);
    };

    openModal = function () {
        $('#modal-box').css( {
            left: $(window).width() / 2 - $('#modal-box').width() / 2,
            top: $(window).height() / 2 - $('#modal-box').height() / 2
        } );
        $('#modal-box').show();
        $('#modal-mask').show();
    };  

    delay(openModal, 2000);

} );


推荐答案

当您为变量分配函数时,您有在使用变量访问函数之前分配它。

When you assign a function to a variable, you have to assign it before you can use the variable to access the function.

如果使用常规语法声明函数而不是将其赋值给变量,则在代码中定义它解析,所以这是有效的:

If you declare the function with regular syntax instead of assigning it to a variable, it is defined when code is parsed, so this works:

$(document).ready( function() {

    delay(openModal, 2000);

    function openModal() {
        $('#modal-box').css( {
            left: $(window).width() / 2 - $('#modal-box').width() / 2,
            top: $(window).height() / 2 - $('#modal-box').height() / 2
        } );
        $('#modal-box').show();
        $('#modal-mask').show();
    };  

});

(注意范围的差异。当你创建变量 openModal 隐式使用它,它将在全局范围内创建,并且可供所有代码使用。当你在另一个函数中声明一个函数时,它只能在该函数内部使用。但是,你使用 var openModal = function(){。)

(Note the difference in scope, though. When you create the variable openModal implicitly by just using it, it will be created in the global scope and will be available to all code. When you declare a function inside another function, it will only be available inside that function. However, you can make the variable local to the function too, using var openModal = function() {.)

这篇关于在调用之前是否必须定义Javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆