javascript 函数的定义和调用方式

图一:
在这里插入图片描述
函数的定义

函数的定义

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA_Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script>
        //  函数的定义方式
        // 1.函数声明方式function关键字(命名函数)
        // 2.函数表达式(匿名函数)
        // 3.new Function()

        // 1. 自定义函数(命名函数)
        function fn() {};

        // 2. 函数表达式(匿名函数)
        var fun = function () {};

        // 3. 利用 new Function('参数1','参数2','参数3');
        // new Function()
        // var fn = new Function('参数1','参数2·...,'函数体')
        // Function里面参数都必须是字符串格式
        // 效率较低
        var f = new Function('console.log(123)');
        f();// 123
        var f1 = new Function('a','b','console.log(a+b)');
        f1(1,2);// 3

        // 4. 所有函数都是 Function 的实例(对象)
        console.dir(f);// 如图一
        console.log(f instanceof Object);//true

    </script>
</head>
<body>

</body>
</html>

在这里插入图片描述



调用方式

调用方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA_Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script>
        // 函数的调用方式

        // 1. 普通函数
        function fn() {
            console.log('啊啦啦啦');
        }
        // fn()   fn.call()

        // 2. 对象的方法
        var o = {
            sayHi:function () {
                console.log('啊啦啦啦');
            }
        }
        // o.sayHi()

        // 3. 构造函数
        function Star() {
            console.log('啊啦啦啦1');
        };
        // new Star();

        // 4. 绑定事件函数
        btn.onclick = function () {};
        // 点击了按钮就可以调用这个函数

        // 5. 定时器函数
        setInterval(function () {} , 1000);
        // 这个函数是定时器自动1秒钟调用一次

        // 6. 立即执行函数
        (function () {
            console.log('啊啦啦啦');
        })();
        // 立即执行函数是自动调用
    </script>
</head>
<body>
<button>按钮</button>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_45949073/article/details/107448119