JavaScript 中的 this

75 阅读1分钟
  • 学习 this 的第一步是明白 this 既不指向函数自身,也不指向函数的词法作用域。 this 实际上是在函数被调用时发生的绑定,它指向什么完全取决于函数在哪里被调用。
function identify(){
    return this.name.toUpperCase()
}

const me = {
    name: 'Sooia'
}

console.log( identify.call(me) ) // SOOIA                                
  • 我们来看看在函数的执行过程中,调用位置如何决定了 this 的绑定对象。

绑定规则

  • 默认绑定
function fool(){
  console.log(this.a)
}

var a = 2;

fool() // 2

  • 隐式绑定
function foo(){
    console.log(this.a)
}

let obj = {
    a: 2,
    foo: foo
}

obj.foo(); // 2

  • 显式绑定 通过foo.call(...),我们可以在调用 foo 时,强制把它的 this 绑定到 obj 上。
function foo(){
    console.log( this.a )
}

let obj = {
    a: 2
}

foo.call( obj ) // 2


  • new 绑定

使用 new 来调用foo(...) 时,我们会构造一个新对象,并把它绑定到 foo(...) 调用中的 this 上。 new 是最后一个可以影响函数调用时 this 绑定行为的方法,我们称之为 new 绑定。

function foo(a){
    this.a = a;
}

let bar = new foo(2);

console.log( bar.a ); // 2

优秀文章链接:深入理解 js this 绑定 ( 无需死记硬背,尾部有总结和面试题解析 ) - SegmentFault 思否