Poznajemy jak działa funkcja call oraz apply w JavaScript. Bez zbędnych wstępów – do dzieła!
Na początku bez strict mode:
window.sth = "blabla";
function display() {
console.log(this.sth);
}
display.call();
//blabla
display.call(globalThis);
//blabla
Teraz ze strict mode:
"use strict";
window.sth = "blabla";
function display() {
console.log(this.sth);
}
display.call(globalThis);
//blabla
display.call();
//reference error
Teraz przykłady z obiektami:
function greet(){
console.log(`Hello ${this.name}! Nice to meet you!`);
}
let john = {
name: 'John'
}
greet.call(john);
//Hello John! Nice to meet you!
greet.call({name: 'Jane'});
//Hello Jane! Nice to meet you!
Teraz z argumentami:
function greet(greeting, end){
console.log(`${greeting} ${this.name}${end} Nice to meet you${end}`);
}
let john = {
name: 'John'
}
greet.call(john, "Hi", ".");
//Hi John. Nice to meet you.
greet.call({name: 'Jane'}, "Whats up", "!");
//Whats up Jane! Nice to meet you!
Teraz możemy zaobserwować jaka jest (niewielka) różnica między call i apply:
function greet(greeting, end){
console.log(`${greeting} ${this.name}${end} Nice to meet you${end}`);
}
let john = {
name: 'John'
}
greet.apply(john, ["Hi", "."]);
//Hi John. Nice to meet you.
greet.apply({name: 'Jane'}, ["Whats up", "!"]);
//Whats up Jane! Nice to meet you!