JavaScript 中的 this 指向

Come back to life, again!

在 JavaScript 中的 this,永遠指向最後調用它的那個對象。

this in JavaScript

1
2
3
4
5
6
7
8
var currentYear = {
yaer: 2019,
print: function () {
console.log(this);
}
};

currentYear.print() //

下面是幾個改變 this 指向的 example:

ES6 Array function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let year = 2019;

let nextYear = {
year: 2020,

func1: function () {
console.log(this.year);
},

func2: function () {
setTimeout(() => {
this.func1()
}, 100);
}
};

nextYear.func2(); // 2020

new Operator

1
2
3
4
5
6
7
8
9
let year = 2019;

function Func () {
this.year = 2018;
}

let lastYear = new Func();

console.log(lastYear.year); // 2018

apply, call, bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let year = 2019;

let nextYear = {
year: 2020,

func1: function () {
console.log(this.year);
},

func2: function () {
setTimeout(function () {
this.func1()
}.apply(nextYear), 100);
// }.call(nextYear), 100);
// }.bind(nextYear)(), 100);
}
};

nextYear.func2(); // 2020

_this = this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let year = 2019;

let nextYear = {
year: 2020,

func1: function () {
console.log(this.year);
},

func2: function () {
let _this = this;
setTimeout(function () {
_this.func1()
}, 100);
}
};

nextYear.func2(); // 2020

0%