JavaScript- funksie Pas toe
Metode Hergebruik
Met die apply()
metode kan jy 'n metode skryf wat op verskillende voorwerpe gebruik kan word.
Die JavaScript application()-metode
Die apply()
metode is soortgelyk aan die call()
metode (vorige hoofstuk).
In hierdie voorbeeld word die vollenaam -metode van persoon op persoon1 toegepas :
Voorbeeld
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
// This will return "Mary Doe":
person.fullName.apply(person1);
Die verskil tussen oproep() en toepas()
Die verskil is:
Die call()
metode neem argumente afsonderlik .
Die apply()
metode neem argumente as 'n skikking .
Die toepassing()-metode is baie handig as jy 'n skikking in plaas van 'n argumentlys wil gebruik.
Die toepassing()-metode met argumente
Die apply()
metode aanvaar argumente in 'n skikking:
Voorbeeld
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName
+ "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
In vergelyking met die call()
metode:
Voorbeeld
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName
+ "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway");
Simuleer 'n maksimum metode op skikkings
Jy kan die grootste getal (in 'n lys van getalle) vind deur die Math.max()
metode:
Voorbeeld
Math.max(1,2,3); // Will return 3
Aangesien JavaScript - skikkings nie 'n max() metode het nie, kan jy
Math.max()
eerder die metode toepas.
Voorbeeld
Math.max.apply(null, [1,2,3]); // Will also return 3
Die eerste argument (nul) maak nie saak nie. Dit word nie in hierdie voorbeeld gebruik nie.
Hierdie voorbeelde sal dieselfde resultaat gee:
Voorbeeld
Math.max.apply(Math, [1,2,3]); // Will also return 3
Voorbeeld
Math.max.apply(" ", [1,2,3]); // Will also return 3
Voorbeeld
Math.max.apply(0, [1,2,3]); // Will also return 3
Streng JavaScript-modus
In JavaScript streng modus, as die eerste argument van die apply()
metode nie 'n objek is nie, word dit die eienaar (objek) van die opgeroep funksie. In "nie-streng" modus word dit die globale voorwerp.