JS中的this指向问题

2019-11-20  本文已影响0人  正义国王

1. this的几种绑定方法

(1)普通函数中的this指向函数的调用点

    function foo() {
        console.log( this.a );
    }
    
    var obj = {
        a: 2,
        foo: foo
    };
    foo(); // 1
    obj.foo(); // 2

(2) call明确绑定

function foo() {
    console.log( this.a );
}

var obj = {
    a: 2
};

foo.call( obj ); // 2

(3)bind 硬绑定

function foo() {
    console.log( this.a);
}

var obj = {
    a: 2
};

var bar = foo.bind( obj );

bar(); //2

(4)new 绑定

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

var bar = new foo( 2 );   //this将指向bar
console.log( bar.a ); // 2

2. 箭头函数的 this

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

也就是上例箭头函数中的 “this” 完全和 foo 中的this相同

var handler = {
  id: "123456",

  init: ()=> {
    console.log(this.id);
  }
};
var id = 0;
handler.init();  //0

箭头函数中的 “this” 和 handler 中的this指向相同,所以将指向handler的调用点即全局作用域,自然this.id=0。但如果此处用的是匿名函数,那么按正常推导,其调用点是handler,那么this.id="123456"

参考:ES6箭头函数

上一篇 下一篇

猜你喜欢

热点阅读