How to use "apply" method in JavaScript

by Jagadish Pulakhandam on 9/11/2012 7:04:44 AM
Rated 0 from 0 votes
Brief: Demonstrates on executing a method from another instance by passing parameters as array using "apply" method in JavaScript
Posted to: Advanced JavaScript Programming/Development tutorials/videos- Object Oriented Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached Source Code/Video demonstrates the following:
  • How to use "apply" method in JavaScript (in place of "call" method)
  • How to execute a method which does not belong to an instance
  • How to send parameters as array to a method being executed on behalf of non-related instance
Source Code:

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
03.<html>
04.<head>
05.    <title></title>
06.    <script type="text/javascript">
07.        //DEMO: using 'Apply' method with parameters
08.                 
09.        //define a function
10.        var Emp = function (vId, vName) {
11.            this.Id = vId;
12.            this.Name = vName;
13.            //method
14.            this.ShowDetails = function (IdCaption, NameCaption) {
15.                alert(IdCaption + this.Id.toString() + ", " + NameCaption + this.Name);
16.            }
17.        }
18. 
19.        //define another function,
20.        //which contains a couple of properties similar to previous function
21.        var Customer = function (vId, vName) {
22.            this.Id = vId;
23.            this.Name = vName;
24.        }
25. 
26.        //create instances
27.        var oCustomer = new Customer(1001, "Jag");
28.        var oEmp = new Emp(2001, "Chat");
29. 
30.       //call ShowDetails on behalf of oCustomer using "apply" (similar to oCustomer.ShowDetails)
31.        oEmp.ShowDetails.apply(oCustomer, ["Id : ", "Name : "]); //'apply' needs parameters as array
32. 
33.        //the above is equivalent to "call" as shown below
34.        //oEmp.ShowDetails.call(oCustomer, "Id : ", "Name : ");
35. 
36.    </script>
37.</head>
38.<body>
39. 
40.</body>
41.</html>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following