Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    JavaScript Inheritance Using Call and Apply

    Using Composition

    Call is a function you can use when you need to invoke one object's methods on another object and also define the scope with the this argument. One way you could do this without using call is through composition. In the following example, cat will execute dog's speak function through composition.

    The problem with the above example is that whether you're calling dog or cat's speak method, the scope is always dog so this.name always returns "Doge". So let's solve this problem with JavaScript's built in call method.

    Using Call and Apply

    And there you have it. Like I mentioned at the beginning of the article, you're able to pass in the scope (this or in this example, our instance of cat). There is another function that's a variation of call and it allows you to pass in an array of arguments instead of explicitly defining each. For example: dog.speak.apply(cat, ["meow"]); This is especially useful when you have a function that accepts a variable number of arguments. Before we wrap up, we'll explain how to use apply towards inheritance by executing the method inside the constructor.

    So in the above example, you have Bird executing Animal's constructor. Bird also takes the additional argument type, but it doesn't need to be passed to Animal. Finally, within the scope of Bird, we define a new function fly, which is only specific to the Bird subclass.

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.