1// this = current execution context (window in browser, global in nodejs)
2console.log(this) // window object
3
4function foo () {
5 console.log(this); // object calling this function
6}
7
8foo(); // undefined
9
10o={ foo }
11o.foo(); // 'o' object logged
1var wF = {
2 w : 560,
3 h : function() { return (312 - 42) / (560 / this.w) + 42; }
4};
5
6alert(wF.h())
7
1var colours = ['red', 'green', 'blue'];
2document.getElementById('element').addEventListener('click', function() {
3 // this is a reference to the element clicked on
4
5 var that = this;
6
7 colours.forEach(function() {
8 // this is undefined
9 // that is a reference to the element clicked on
10 });
11});
12
1In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
2
3With arrow functions, the this keyword always represents the object that defined the arrow function.
1// Im Webbrowser ist das window Objekt das globale Objekt:
2console.log(this === window); // true
3
4a = 37;
5console.log(window.a); // 37
6
7this.b = "MDN";
8console.log(window.b); // "MDN"
9console.log(b); // "MDN"
10