JavaScript Function Apply
- Vorige pagina JS-functie Call
- Volgende pagina JS-functie binden
method reuse
By apply()
method, you can write methods for different objects.
JavaScript apply() method
apply()
The method with call()
The methods are very similar:
In this example,person
of fullName
The method isapplicationto person1
:
Voorbeeld
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName: "Bill", lastName: "Gates", } person.fullName.apply(person1); // Will return "Bill Gates"
The difference between call() and apply()
The difference is:
call()
The method accepts parameters separately.
apply()
The method accepts parameters in array form.
If you want to use an array instead of a parameter list, then apply()
The method is very convenient.
Parameterized apply() method
apply()
Method accepts parameters in an array form:
Voorbeeld
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:\"Bill\", lastName: "Gates" } person.fullName.apply(person1, ["Oslo", "Norway"]);
with call()
Method comparison:
Voorbeeld
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:\"Bill\", lastName: "Gates" } person.fullName.call(person1, "Oslo", "Norway");
de max-methode simuleren op een array
U kunt Math.max()
Methode vinden van (getal)lijst het grootste getal:
Voorbeeld
Math.max(1,2,3); // zal 3 teruggeven
Omdat JavaScript-arrays geen max()-methode hebben, kunt u Math.max()
Methode.
Voorbeeld
Math.max.apply(null, [1,2,3]); // zal ook 3 teruggeven
De eerste parameter (null) is niet van belang. In dit voorbeeld wordt het niet gebruikt.
Deze voorbeelden zullen hetzelfde resultaat geven:
Voorbeeld
Math.max.apply(Math, [1,2,3]); // zal ook 3 teruggeven
Voorbeeld
Math.max.apply(" ", [1,2,3]); // zal ook 3 teruggeven
Voorbeeld
Math.max.apply(0, [1,2,3]); // zal ook 3 teruggeven
JavaScript-strict modus
In JavaScript-strict modus, als apply()
De eerste parameter is geen object, dan wordt het de eigenaar van de aangeroepen functie (object). In de 'niet-strict' modus wordt het het globale object.
- Vorige pagina JS-functie Call
- Volgende pagina JS-functie binden