this

34 阅读1分钟

this是一个关键字

this指向

  • 谁调用this,this就指向谁

全局

console.log(this)
function fn(){
    console.log(this)
}
//在全局调用的函数,this也是指向全局
fn()

对象

var obj = {
    name:"cxm",
    test:function(){
        console.log(this)
    }
}
//这里的this指向的是obj这个对象
obj.test()

事件绑定

  • dom0和dom2中的this都指向事件绑定的那个节点
box.onclick = function(){
    //这里的this指向box这个节点
    console.log(this)  
}

改变this指向

  • 三个方法

call 和 apply

  • callapply方法允许直接调用函数,并且可以显式地指定函数内部的this的值。

  • 区别在于call方法接受参数列表,而apply方法接受一个包含参数的数组。

function fn1(a, b, c) {
    console.log(this)
    console.log(a, b, c)
}
fn1(1, 2, 3)  //this指向window 
// apply
fn1.apply(person, [1, 2, '3'])     //this指向person,传递参数用数组
// call
fn1.call(person, 1, 2, "true")  //this指向person,第一个参数是改变this指向,后面的是实参

bind

  • bind方法创建一个新函数,将其内部的this指向指定的对象。
  • 不允许直接调用
var obj = {
    name: "aaaa",
    show() {
        console.log(this)
        console.log(this.name)
    }
}
obj.show()  //this指向obj,this.name为aaaa
// 【注】bind方法不会立即执行,后需要加上小括号执行函数
obj.show.bind(person)() //this指向person,this.name为杨超越

三个方法的异同

  • 它们都能改变函数的this指向
  • bind不会立即执行,需要手动执行
  • apply和call都会立即执行,区别在于apply的第二个参数是一个数组