1、什么是this
this一般指向的是调用它的对象,比如调用它的上下文是window对象,那就是指向window对象,如果调用它的上下文是某对象就是指向某对象……
//例如
<script>
console.log(this) //window
</script>
//这里调用者是全局对象window,所以this指向window
<script>
var person = {
name: 'dog',
say: function () {
console.log(this);
}
}
//这里调用者是person对象,所以this指向person
person.say(); //person
</script>
2、用来干嘛
this在一般情况下,是指向函数的上下文,可以处理一些作用域下的事件调用
如果想要引用某对象的方法,就不用写太多重复代码,直接用this调用某对象的方法
3、怎么在代码中使用
console.log(this); //window
var person = {
name: 'dog',
say: function () {
console.log(this); //person
console.log(this.name); //dog
}
}
person.say();
console.log(this.person.name); //dog
4、改变this指向
4.1引入call、bind、apply
4.1.1区别
共同点
- 都是函数的内置方法
- 都可以改变函数执行的上下文
注:改变上下文可以为程序节省内存空间,减少不必要的内存操作
通俗易懂解释改变上下文:
小张在公司有个快递要拿,刚好有事,自己拿不了,他就安排小王拿,这里小张本来是拿快递的执行上下文,因为有事,就改变拿快递的执行上下文,变成了小王,节约了小张的时间,他就不用另外安排时间去拿快递了4
不同点
- call、apply是立即执行,bind是不会立即执行,而是返回一个回调函数,执行时需要加个()
- call格式为call(this.obj,arg,arg,...) , 接收一个或多个由逗号隔开的参数
- apply格式为apply(this.obj,[argArray]),只接收两个参数,一个是新this对象,一个是数组参数(类数组对象)
bind格式为bind(this.obj,arg,arg,arg,...),接收一个或者多个有逗号隔开的参数
4.1.2怎么用
//call 这里能传递多个参数,也能传递参数列表 var name = 'cat' var person = { name: 'dog', say: function () { console.log(this) //window console.log(this.name) //cat console.log(arguments) //arguments对象 console.log(...arguments) //pig bird }, } //这里把this指向对象修改成window,此时this.name应该为cat person.say.call(this, 'pig', 'bird') person.say.call(this, ['pig', 'bird']) 注: arguments对象是一个类数组对象,它具有数组长度length属性,但是又不同于数组,在参数传递上,不管对象函数是否设置形参,都可以接收用户传过来的参数,可以把参数通过数组形式的进行传递
//apply 这里只能传递数组参数,否则会报错 var name = 'cat' var person = { name: 'dog', say: function () { console.log(this) //window console.log(this.name) //cat console.log(arguments); //arguments对象 console.log(...arguments);//pig bird } } //这里this指向为window person.say.apply(this, ['pig', 'bird']) person.say.apply(this, 'pig', 'bird')//报错
//bind
var name = 'cat'
var person = {
name: 'dog',
say: function () {
console.log(this) //window
console.log(this.name) //cat
console.log(arguments);//arguments
console.log(...arguments);//pig bird
}
}
//这里this指向为window,必须加个()才算执行
person.say.bind(this, 'pig', 'bird')()
//也可以写成
var p = person.say.bind(this, 'pig', 'bird')
p()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。