A simple example of the Javascript ‘Call’ function

I was asked about function.call() the other day during a discussion with a co-worker, and came up with this example off the top of my head.  There are many, many uses of call().  In addition to accepting an object as a parameter to replace the called function’s this, it also accepts an arbitrary number of arguments that will be passed into the called function.  Better examples can be found in the Mozilla Developer Network JavaScript Reference.

// A constructor function for a Dog
var Dog = function(name){
this.name = name;

Dog.prototype.bark = function bark(){console.log(this.name + " barks!");};

// Fred is a Dog.
// Fred can bark, because all Dogs can bark.
var fredDog = new Dog("Fred");
fredDog.bark(); // => "Fred barks!"

// A constructor function for a Cat
var Cat = function(name){ this.name = name; };

// Bill is a Cat
var billCat = new Cat("Bill");

// Normally, Cats cannot bark,
// but Bill is an exception and has learned how to bark like Fred
fredDog.bark.call(billCat); // => "Bill barks!"

When bark() is invoked with the call() function, billCat takes the place of this within the bark function of Dog, so this.name is a reference to billCat.name instead of fredDog.name.

1 Comment

  1. Mary Beth Murray In the summer of 2010, Ken Shaw, along with his dog Gracie, will thru-hike the Finger Lakes Trail from the Catskill Mountains to the New York, Pennsylvania brdeor in Allegany State Park as a fundraiser for Theatre Of Youth (TOY) located in Buffalo, NY. Ken is the Head of Design at TOY.Gracie, a Whippet mix, was adopted by Ken in 2009. She has been training in RuffWear boots, pack and trail leash. She loves her hikes with Ken and is very comfortable on the training trails with her gear. Gracie will begin their 50 day journey on May 15, 2010. Each hiking day is 8 to 18 miles. Gracie will join Ken on the trail that has been deemed safe terrain for pooches. Ken has arranged for Road Spotters and Trail Angles to take care of Gracie for the unfriendly parts of the trail. Gracie and Ken will cross rivers, climb mountains, descend into ravines, cross 1 National Forest, four State Parks, 41 State Forests and 3 Wildlife Management Areas. Additionally, their adventure will have them pumping and filtering water, cooking food on a portable stove, sleeping in tents or open front shelters, hanging bear bags, building fires and hopefully not get lost in the woods! The Kids at the Theatre think this is all very exciting and most especially are interested in Graciee28099s adventures(I am a friend of the Theatre and a strong supporter of animal rescue programs, the Theatre and the Finger Lakes Trail. I love this story and wanted to share a taste of it.)

Leave a Reply

Your email address will not be published.


© 2016 Eric Terpstra

Theme by Anders NorenUp ↑