JavaScript学习笔记——关于this
this有四种情况
- 当函数调用时,this指向全局对象 在浏览器环境下就是window对象。
<script> var name = tom; function test() { console.log(this.name); alert(this == window)//true } test()//tom </script>
- 当对象方法调用时,this 指向调用对象
-
当函数被保存为一个对象的属性时,它就可称为这个对象的方法。
<script> var obj = { name: tom, sayName: function(){ console.log(name:,this.name); } } obj.sayName()//name: tom </script>
(1)闭包使用普通函数
<script> var name = tom; var obj = { name: jacket, sayName: function(){ //闭包中的this指向调用这个闭包的对象,也就是window对象 //并且匿名函数的执行环境具有全局性,所以这里的this指向全局环境 return function(){ console.log(name:,this.name); } } } obj.sayName()()//name: tom //等同于以下代码 var fun = obj.sayName(); fun()//name: tom fun()方法是window对象调用的,其this指向window对象 </script>
(2)闭包使用箭头函数
<script> var obj = { name: jacket, sayName: function(){ return () => { console.log(name:, this.name); } } } obj.sayName()()//name: jacket </script>
总结:箭头函数没有自己的 this,当在内部使用了 this时,它会指向最近一层作用域内的 this。在函数中需要使用闭包的时候,用箭头函数就很方便了。
- 当构造函数调用时,this 指向new 出的对象
<script> function Person(name,age){ this.name=name; this.age=age; this.sayname=function(){ alert(this.name); }; } var p1=new Person(tom,10); //this指向new实例,p1.name=name alert(p1.name); //tom </script>
- 当apply和call调用时,this指向方法传入的第一个参数 call(this,item...)、apply(this,array...)这两个方法可以让我们构建一个参数数组传递给调用函数,也允许我们改变this的值/函数的执行环境
<script> var name = tom; var obj = { name: jacket, sayName() { console.log(name:, this.name); } } obj.sayName.apply()//name: tom //apply()的参数为空时,默认调用全局对象window obj.sayName.apply(obj)//name: jacket </script>
补充
this绑定优先级: new > bind > call(apply) > obj.func() > 默认绑定
立即执行函数的写法: 用括号运算符 双括号: (function(){语句})()将函数体变化表达式,后面跟括号运算符立即执行 (function(){语句}())将整个函数声明和括号运算符变成表达式 三括号: ((function(){语句})()) 其他操作符转化表达式 var res =function test(){语句}()