Javascript中的this关键字指向
this关键字介绍
-
面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。 在方法中,this 表示该方法所属的对象。 如果单独使用,this 表示全局对象。 在函数中,this 表示全局对象。 在函数中,在严格模式下,this 是未定义的(undefined)。 在事件中,this 表示接收事件的元素。 类似 call() 和 apply() 方法可以将 this 引用到任何对象。
不同情况下的this
1.对象调用方法中的this
在方法中,this 表示该方法所属的对象
// 创建一个对象 var Person={ name:"王富贵", sex:男, fn:function(){ console.log(this.name+ +this.sex) } } Person.fn()//this指向了Person对象 .前面是谁this就指向睡
2.在全局使用this(单独使用)
在全局使用的时候this表示全局对象window
<script> console.log(this) </script>
3.函数中的this
在函数中,this表示全局对象window
4.函数严格模式下
在函数中,在严格模式下,this 是未定义的(undefined)
<script> function fn(){ "use strict"//严格模式 console.log(this) } fn()//undefined </script>
5.事件中的this
在事件中,this 表示接收事件的元素
<button class="btn">事件中的this</button> <script> let btn=document.querySelector(.btn) //点击事件 btn.onclick=function(){ console.log(this) //打印this this.style.display="none" //点击后按钮消失 } </script>
点击后按钮消失,打印this
6.构造函数中的this
构造函数中的this指向当前实例
function Person(){ this.name=Jack } Person.prototype={ fn(){ console.log(this) } } let p1=new Person() console.log(p1) //Person {name: "Jack"} console.log(p1.name) //Jack p1.fn() //Person {name: "Jack"}
7.箭头函数没有this
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象 箭头函数本身没有自己的this, 绑定定义时所在的作用域,而不是指向运行时所在的作用域。所以其内部的this指向定义该箭头函数时,外层代码块的this,即箭头函数的this指向固定化
call()、apply()、bind() 的用法
call 、bind 、 apply 这三个函数的作用是改变this指向
-
用在函数后面 例如 fn().call()或者obj.fn().call(),参数可以是各种类型 call(this指向对象,参数,...,参数) apply(this指向对象,[参数,...,参数]) bind(this指向对象,参数,...,参数)()由此可见,bind的返回值是一个函数
var obj={ name:王富贵, age:18, myFun:function(like,hate){ console.log(this.name,this.age,"喜欢"+like,"讨厌"+hate) } } var res={ name:张三, age:20 } //call obj.myFun.call(res,打篮球,香菜)//张三 20 喜欢打篮球 讨厌香菜 obj.myFun.call(res,[打篮球,香菜])//张三 20 喜欢打篮球,香菜 讨厌undefined //apply obj.myFun.apply(res,[玩游戏,可乐])//张三 20 喜欢玩游戏 讨厌可乐 obj.myFun.bind(res,吃火锅,唱歌)()//张三 20 喜欢吃火锅 讨厌唱歌 //bind obj.myFun.bind(res,[吃火锅,唱歌])()//张三 20 喜欢吃火锅,唱歌 讨厌undefined