Created by
this ≅ global object
Window
global
this
depends on how a function is invoked!this ≅ global object
Window
global
function f(){
console.log( "this in function call:", this );
}
f();
// Window
this = undefined
"use strict";
function f(){
console.log( "this in strict function call:", this );
}
f();
// undefined
more on Strict Mode: MDN JavaScript Reference
this = the object
the method is called on
var obj = {
foo: function(){
console.log(`this = ${this}`);
}
};
obj.foo();
// this = [object Object]
class A{
method1(){
console.log(`This in method: ${this}`);
}
static staticMethod(){
console.log(`This in static method: ${this}`);
}
}
let obj = new A();
obj.method1()
A.staticMethod()
this = the object being constructed
function Constructor(id){
this.id = id;
console.log(`this = ${this}`);
// this = [object Object]
};
var obj1 = new Constructor(1);
apply()
method calls a function with a given this value, and arguments provided as an array
func.apply(thisArg, [argsArray])
this
value inside function func
will be equal to the object passed by thisArg
argument
const maria = {name: "Maria", age:18};
function update(name, age){
this.name = name;
this.age = age;
}
console.log("maria before", maria);
update.apply(maria, ["Maria Ivanova", 23]);
console.log("maria after", maria);
call()
method calls a function with a given this value, and arguments provided individually (comma separated)
func.call(thisArg, arg1, arg2, ...)
this
value inside function func
will be equal to the object passed by thisArg
argument
const maria = {name: "Maria", age:18};
function update(name, age){
this.name = name;
this.age = age;
}
mariaNewRecord = ["Maria Ivanova", 23];
console.log("maria before", maria);
update.apply(maria, mariaNewRecord );
console.log("maria after", maria);
bind()
method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.this
value inside function func
will be equal to the object passed by thisArg
argument
func.bind(thisArg[, arg1[, arg2[, ...]]])
const maria = {name: "Maria", age:18};
function update(name, age){
this.name = name;
this.age = age;
}
console.log("maria before", maria);
var updateMaria = update.bind(maria,"Maria Ivanova", 23);
updateMaria();
console.log("maria after", maria);
addEventListener callback
addEventListener callback
setTimeout/setInterval callback
setTimeout/setInterval callback
See the Pen Task1: Execute callback after 2 seconds ('this' problem) by Iva Popova (@webdesigncourse) on CodePen.
See the Pen Task:Fix the bug ('this' problem) by Iva Popova (@webdesigncourse) on CodePen.
These slides are based on
customised version of
framework