JS中this的指向
this
的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this
到底指向谁,实际上this
的最终指向的是那个调用它的对象。
实例
定义函数与对象并调用,注意只有调用函数才会使this
指向调用者,但箭头函数除外。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| function s(){ console.log(this); }
s();
var s1 = { t1: function(){ console.log(this); s(); }, t2: () => { console.log(this); }, t3: { tt1: function() { console.log(this); } }, t4: { tt1: () => { console.log(this); } }, t5: function(){ return { tt1: () => { console.log(this); } } } } s1.t1(); s1.t2(); s1.t3.tt1(); s1.t4.tt1(); s1.t5().tt1();
|
比较特殊的例子,我们调用同一个方法,但是得到的this
是不同的,要注意实际上this
的最终指向的是那个调用它的对象。
1 2 3 4 5 6 7 8 9 10 11 12 13
| var s1 = { t1: function(){ console.log(this); } } s1.t1(); var p = s1.t1; p();
console.log(p);
|
改变this指向
1 2
| 使用 apply、call、bind可以改变this的指向,可以参考 https://github.com/WindrunnerMax/EveryDay/blob/master/JavaScript/apply%E3%80%81call%E3%80%81bind.md
|
参考
1
| http://www.ruanyifeng.com/blog/2018/06/javascript-this.html
|