简单概括 this指向,以及概括apply、call、bind的区别

86 阅读1分钟

1.this永远指向最后一个调用他的对象

例子:

let name = "zhangsan"
let a = {
    name:"lisi",
    fn:function(){
        console.log(this.name) // "lisi"
    }
}

a.fn()

因为fn被a调用,所以指向a,这里输出的为a中的name

2.箭头函数的 this 始终指向函数定义时的 this,而非执行时。

众所周知,ES6 的箭头函数是可以避免 ES5 中使用 this 的坑的。箭头函数需要记着这句话:“箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined”。

var name = "windowsName"; 
var a = { 
    name : "Cherry",
    func1: function () { 
        console.log(this.name) 
       },
    func2: function () { 
        setTimeout( () => { this.func1() },100); 
       } 
     }; 
    a.func2() // Cherry

3.apply、call、bind

apply用法: func.apply(thisArg, [argsArray])
call用法: func.call(thisArg, arg1,arg2,...)
bind用法: func.bind(thisArg, arg1,arg2,...)()
相同点:都用于改变函数的this指向,this指向第一个参数。
不同点:参数的传法不一样,且bind最后需要调用一次。

参考文章:# this、apply、call、bind