How to use "call" method in JavaScript

by Jagadish Pulakhandam on 9/10/2012 8:48:52 AM
Rated 0 from 0 votes
Brief: Demonstrates on using "call" 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:
  • Create two instances from two different classes (function constructors) in JavaScript
  • Call a method available in an instance on behalf of another instance (data will be from another instance)
  • Make method behave like it is from another instance (of another class), temporarily.
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 'Call' method
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 () {
15.                alert("Id = " + this.Id.toString() + ", Name = " + 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 (temporarily, "ShowDetails" becomes a method of oCustomer)
31.        //similar to oCustomer.ShowDetails (only for the statement)
32.        oEmp.ShowDetails.call(oCustomer);
33. 
34.        //oEmp.ShowDetails().call(oCustomer);  //this line is different from the above, calls oEmp.ShowDetails()
35.    </script>
36.</head>
37.<body>
38. 
39.</body>
40.</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