What's 'this' ?

Åbn DevTools og sammenlign med JavaScript kode

console.log("this: "+this); //window

// in functions:

function test1(){

console.log("this in a function: "+this); //window - hvis ikke i strict mode

}

test1();

function test2(){

"use strict";

console.log("this in a strict mode function: "+this); //undefined
- strict mode does not allow default binding

}

test2();

const test3 = () => {

"use strict";

console.log("this in a strict mode Arrow function: "+this); //window
- arrow functions don't bind 'this'

}

test3();

//JQUERY:

$(function(){

"use strict";

console.log("this in JQuery: "+this); //document

console.log("------------");

});

Vanilla buttons:

document.querySelector("#b1").addEventListener("click", function(){

console.log("this in a button standard function: "+this);
//button - this is bound in normal functions.

});

document.querySelector("#b2").addEventListener("click", ()=>{

console.log("this in an button arrrow function: "+this);
//window - arrow functions don't bind 'this'.

});

JQuery buttons:

$("#b3").click(function(){

console.log("this in a JQuery standard function: "+this);
//button - this is bound in normal functions.

});

$("#b4").click(()=>{

console.log("this in a JQuery Arrow function: "+this);
//document - this not bound in arrow functions.

});