What is apply() method in JavaScript

Recently I wrote post on What is Bind method in JavaScript and about What is call() method in JavaScript In this post we will take a look on apply method in JavaScript.

apply() method is exactly the same as call() method with minor difference in passing arguments.

Alike call() method using apply() method also, you can invoke a function on given object. Let us understand with some example. Consider that you have a function GreetingMessage() as following ,

1
2
3
4
function GreetingMessage() {
 
alert( "Hello Geek !" );
  };

And you have an object Student as following,

1
var Student = {};

You can call function GreetingMessage on object Student as following,

1
GreetingMessage.apply(Student);

As output you should get following output,


Apply() method allows you to invoke function which parameter is array of not fixed length. Apply() method pass arbitrary length array as arguments to function.

Let us consider following example. In below example we are calculating sum of the array in function FindSum().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function FindSum(e) {
 
var sum = 0;
  for ( var i = 0 ; i < arguments.length ; i++) {
 
sum = sum + arguments[i];
 
}
  return sum;
  };
 
var Student = {
  };
 
 
var sumOfMarks = FindSum.apply(Student, [12, 45, 11, 56, 189]);
  alert(sumOfMarks);

Essentially above you are passing dynamic array to apply method. In function you can access passed parameters using arguments. As output you will get sum of passed array,


To summarize,

  • apply() method takes at least one parameter.
  • First parameter is object on which function to be invoked
  • Second parameter onwards get passed to the function to be invoked.
  • It passes arbitrary length array to function

This was a brief discussion of apply() method is JavaScript. I hope you find this post useful. Thanks for reading.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值