Metoda JavaScript Function call () volá funkci s danou touto hodnotou a argumenty poskytované jednotlivě.
Syntaxe call()
metody je:
func.call(thisArg, arg1,… argN)
Tady func
je funkce.
call () Parametry
call()
Metoda bere v:
thisArg
- Hodnotathis
poskytovaná pro volánífunc
.arg1,… argN
(nepovinné) - Argumenty pro funkci.
Vrátit hodnotu z hovoru ()
- Vrátí výsledek volání funkce se zadanou
this
hodnotou a argumenty.
Použitím call()
můžeme použít funkce patřící jednomu objektu, které mají být přiřazeny a vyvolány pro jiný objekt.
Příklad 1: Použití call ()
function greet() ( const string = `My name is $(this.firstName) $(this.secondName). I am $(this.age) years old.`; console.log(string); ) const human = ( firstName: "Judah", lastName: "Parker", age: 26, ); greet.call(human); // My name is Judah undefined. I am 26 years old.
Výstup
Jmenuji se Juda undefined. Je mi 26 let.
Příklad 2: Použití call () k řetězovým konstruktorům
function Animal(name, age) ( this.name = name; this.age = age; ) function Horse(name, age) ( Animal.call(this, name, age); this.sound = "Neigh"; ) function Snake(name, age) ( Animal.call(this, name, age); this.sound = "Hiss"; ) const snake1 = new Snake("Harry", 5); console.log(snake1.name, snake1.age, snake1.sound); const horse1 = new Horse("Arnold", 8); console.log(horse1.name, horse1.age, horse1.sound);
Výstup
Harry 5 Hiss Arnold 8 Neigh
Poznámka: Rozdíl mezi call()
a apply()
je v tom, že call()
přijímá seznam argumentů, zatímco apply()
přijímá jednu řadu argumentů.
Doporučené čtení: Použít funkci JavaScriptu ()