JS中的this指向问题
-
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
- 箭头函数根本没有自己的this,其内部的this就是外层代码块的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箭头函数