function foo () { }
var foo = function () { }
函数声明:
函数表达式:
这是一个根据条件定义函数的例子:
if (true) { function f () { console.log(1) } } else { function f () { console.log(2) } }
以上代码执行结果在不同浏览器中结果不一致。
不过我们可以使用函数表达式解决上面的问题:
var f if (true) { f = function () { console.log(1) } } else { f = function () { console.log(2) } }
this
指向的不同场景函数的调用方式决定了 this
指向的不同:
调用方式 | 非严格模式 | 备注 |
---|---|---|
普通函数调用 | window | 严格模式下是 undefined |
构造函数调用 | 实例对象 | 原型方法中 this 也是实例对象 |
对象方法调用 | 该方法所属对象 | 紧挨着的对象调用的this |
事件绑定方法 | 绑定事件对象 | 当前的实例对象 |
定时器函数 | window | window |
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <body> </body> </html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <script> /* * * 函数中的this的指向 * * * 普通函数中的this是谁?-----window * 对象.方法中的this是谁?----当前的实例对象 * 定时器方法中的this是谁?----window * 构造函数中的this是谁?-----实例对象 * 原型对象方法中的this是谁?---实例对象 * * * */ //严格模式: "use strict";//严格模式 function f1() { console.log(this);//window } f1(); //普通函数 function f1() { console.log(this); } f1(); //定时器中的this var inter=setInterval(function () { console.log(this); clearInterval(inter); }, 1000); //构造函数 function Person() { console.log(this); // 对象的方法 this.sayHi = function () { console.log(this); }; } //原型中的方法 Person.prototype.eat = function () { console.log(this); }; var per = new Person(); console.log(per); per.sayHi(); per.eat(); //BOM:中顶级对象是window,浏览器中所有的东西都是window的 </script> </head> <body> </body> </html>
所有函数都是 Function
的实例
也就是说所有的函数实际上都是Function的构造函数创建出来的实例对象
forEach忘了的可以看一下菜鸟的教程:
https://www.runoob.com/jsref/jsref-foreach.html
第一个参数就是遍历到的当前元素其本身
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <script> //数组可以存储任何类型的数据 var arr=[ function () { console.log("1"); }, function () { console.log("2"); } , function () { console.log("3"); } , function () { console.log("4"); }, function () { console.log("5"); } ]; //回调函数:函数作为参数使用 arr.forEach(function (ele) { ele(); }); </script> </head> <body> </body> </html>