关于javascript:javascript高级3

7次阅读

共计 1897 个字符,预计需要花费 5 分钟才能阅读完成。

创立函数的三种款式

1.function 申明的一般函数(命名函数)
2. 函数表达式(匿名函数)
3.new Function()

var fn =new Function(‘ 参数 1 ′,’ 参数 2 ’,…,’ 函数体);

  • Function() 外面的参数都是字符串格局
  • 第三种形式执行效率比拟低,也不不便书写,因而较少应用
  • 所有的函数都是 Fnction 的实例对象
  • 函数也属于对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 函数的定义和调用形式 </title>
</head>
<body>
<script>
    // 自定义形式
 function fn() {}
    // 函数表达式
 var fn = function() {}
    // 利用 new Function('参数 1','参数 2','函数体')
 var f = new Function('a','b','return a+b')
    console.log(f(1,2));
    console.dir(f);
    // 用来判断 f 是否是一个对象
 console.log(f instanceof Object)
</script>
</body>
</html>

不同函数的调用形式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button> 按钮 </button>
</body>
<script>
    // 函数的调用形式
 // 1. 一般函数的调用
 function fn() {console.log('hello word')
    }
    fn()
    // 2. 对象类的函数调用
 var obj = {say: function () {return 'hello word'}
    }
    console.log(obj.say())
    // 3. 构造函数的调用
 function Star(name, age) {
        this.name = name;
        this.age = age;
    }
    var star1 = new Star('尧子陌', '18');
    console.log(star1.name)
    //4. 事件函数的调用
 var bth = document.querySelector('button');
    bth.addEventListener('click', function () {console.log('事件函数')
    })
    // 5. 定时器函数
 setInterval(function () {console.log('定时器函数')
    }, 5000)
</script>
</html>

自执行函数

顾名思义:本人调用的函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 自执行函数 </title>
</head>
<body>
<script>
    (function () {alert('hello word')
    })()
</script>
</body>
</html>

this 的指向问题

函数外部的 this 指向,当咱们调用的时候才确定

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title> 函数的 this 指向 </title>
    </head>
    <body>
        <button> 按钮 </button>
    </body>
    <script>
        // 函数的调用形式

        // 1. 一般函数的调用
        function fn() {console.log(this) //windows

        }

        fn()
        // 2. 对象类的函数调用
        var obj = {say: function() {console.log(this) // 指向 o 这个对象
            }
        }
        obj.say()

        // 3. 构造函数的调用
        function Star(name, age) {console.log(this) // 构造函数中的 this 指向的是它的实例化 star
            this.name = name;
            this.age = age;

        }

        var star1 = new Star('尧子陌', '18');
        //4. 事件函数的调用
        var bth = document.querySelector('button');
        bth.addEventListener('click', function() {console.log(this) // 事件函数中的 this 指向的是它的调用者 bth 按钮
        })

        // 5. 定时器函数
        setInterval(function() {console.log(this) // 定时器中的 this 指向的是 windows
        }, 5000)
    </script>
</html>

正文完
 0