JS的一些总结(函数声明和函数表达式的区别,函数中的this指向的问题,函数不同的调用方式,函数也是对象,数组中的函数调用)
一、函数声明和函数表达式的区别:
- 函数声明放在if——else语句中,在IE8中会出现问题
- 函数表达式则不会
<script> if(true){ function f1(){ console.log("我是第一个函数"); } }else{ function f1(){ console.log("我是第二个函数"); } } f1();//我是第一个函数 f1();//我是第二个函数(IE8) //函数声明的函数,放在if--else语句中,在IE8中显示的不一样 //但是当使用函数表达式的方法,却不会 if(true){ var f2=function(){ console.log("我是第一个函数"); } }else{ var f2=function (){ console.log("我是第二个函数"); } } f2();//我是第一个函数 </script>
二、函数中的this指向的问题
- 普通函数中的this------------window
- 定时器中的this---------------window
- 构造函数中的this------------实例对象
- 对象。方法中的this----------当前的实例对象
- 原型方法中的this----------实例对象
- 严格模式下的this-----------undefined
<script> //1.普通函数中的this------------window function f1(){ console.log(this); } f1();//Window //2.定时器中的this---------------window setInterval(function(){ console.log(this);//Window },1500) //3.构造函数中的this------------实例对象 //4.对象。方法中的this----------当前的实例对象 //5.原型方法中的this----------实例对象 function Person(){ this.name=name; this.show1=function(){ console.log(this); } } Person.prototype.show2=function(){ console.log(this); } var per=new Person("小明"); per.show1();//Person {name: "", show1: ƒ} per.show2();//Person {name: "", show1: ƒ} //6.严格模式下的this-----------undefined function f2(){ "use strict"; console.log(this); } f2();//undefined </script>
三、函数不同的调用方式
- 普通函数-------直接函数名()
- 构造函数-------通过new来调用,创建对象
- 对象方法------点语法,对象.方法调用
四、函数也是对象,对象不一定是函数
- 函数有prototype原型,是对象,对象中有__proto__,原型是对象
- 如果一个对象里面有prototype又有__proto__,既是原型也是对象
- Math是对象,但是没有__proto__,不是函数
- 所有的函数实际上都是Function的构造函数创建出来的实例对象
五、数组中的函数调用(forEach)
<script> var arr=[ function f1(){console.log("f1函数")}, function f2(){console.log("f2函数")}, function f3(){console.log("f3函数")}, function f4(){console.log("f4函数")} ]; arr.forEach(function(ele){ ele();//f1函数 f2函数 f3函数 f4函数 }); </script>
【转载文章务必保留出处和署名,谢谢!】