Created by
window object
global object
console.log(`THIS in global scope:`);
console.dir(this);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>thisInGlobalScope </title>
</head>
<body>
<script src="thisInGlobalScope.js"></script>
</body>
</html>
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]
this
= the object being constructed
function Constructor(id){
this.id = id;
console.log(`this = ${this}`);
};
var obj1 = new Constructor(1);
// this = [object Object]
in method call this
will be bound to the object, as well
function Constructor(id){
this.id = id;
console.log(`this in constructor: ${this}`);
this.showID = function(){
console.log(`ID: ${id}`);
console.log(`this in a method: ${this}`);
}
};
var obj1 = new Constructor(1);
obj1.showID();
const btn = document.querySelector("button");
btn.addEventListener('click', function(event) {
console.dir(this);
})
// OUTPUT: button
apply()
, call()
and bind()
function methodsapply()
, call()
and bind()
function methods
func.apply(thisArg, [argsArray])
this
value inside function func
will be equal to the object passed by thisArg
argument.The other arguments are passed as an array to the function being called.
function update(name, age){
this.name = name;
this.age = age;
}
let maria = {name: "Maria", age:18};
console.log("maria before", maria);
update.apply(maria, ["Maria Ivanova", 23]);
console.log("maria after", maria);
func.call(thisArg, arg1, ... , argN)
this
value inside function func
will be equal to the object passed by thisArg
argument.The other arguments are passed as list to the function being called.
function update(name, age){
this.name = name;
this.age = age;
}
let maria = {name: "Maria", age:18};
console.log("maria before", maria);
update.call(maria, "Maria Ivanova", 23);
console.log("maria after", maria);
func.bind(thisArg, arg1, ... , argN)
this
keyword set to the provided value (thisArg), with a given list of arguments preceding any provided when the new function is called
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);
Fix the problem, so that we see in console numbers 1,2,3 instead of NaNs, on each click
Fix the problem in countdown function, so that we see in console the numbers 1,2,3 instead of NaN
These slides are based on
customised version of
framework