创立函数的三种款式
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>