Advertisement
JavaScript & AJAX

Quick Tip: Calling JavaScript Methods on Other Objects

by

You’ll never stop being surprised by JavaScript. In this quick tip, I’m going to show you how to use the JavaScript methods, call and apply, to call your functions of other objects. Don’t know what I mean? Let’s get started!

View Screencast

Press the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!

Using Call and Apply

Here’s the scenario: we have two objects:

var joe = {
    name : "Joe",
    greet : function (name) {
        alert(this.name + " says hello to " + name);
    }
};

var jill = {
    name : "Jill"
};

It’s pretty simple to get Joe to greet Jill:

joe.greet("Jill");

But how can we get Jill to greet Joe? She doesn’t have a greet method (and let’s assume we can’t / won’t / shouldn’t give her one). Well, because everything in JavaScript—including functions—is an object, everything can have a method, or a function that can be called from it. Functions are given two methods that allow you to call them in different contexts.

The context of a method is basically the object that will be this when the function is called. In our greet method, this refers to the object joe, because that’s what it is a part of.

Now, try this:

joe.greet.call(jill, "Joe");

The call method on JavaScript functions allows you to change the function’s context. The first parameter we pass in will be the new context: in this case, that’s jill. Subsequent parameters are the parameters to the function you’re calling. In this case, “Joe” will be passed to greet. If you run this, you’ll get an alert box with the message “Jill says hi to Joe.”

There’s also an apply method; the only difference is that it takes the parameters of the method as an array, rather than as raw parameters, a la the call method.

joe.greet.call(jill, ["Joe"]);

If you have a hard time remembering whether it’s call or apply that takes the array, remember that apply and array both start with ”a.”

Thanks for reading!

Related Posts
  • Code
    Web Development
    Build Your Own Yeoman GeneratorYeoman wide retina preview
    Take a look at some of the more interesting features of Yeoman by learning how to build your own Yeoman generator.Read More…
  • Code
    JavaScript & AJAX
    Testing in Node.jsNodejs testing chai retina preview
    A test driven development cycle simplifies the thought process of writing code, makes it easier, and quicker in the long run. But just writing tests is not enough by itself, knowing the kinds of tests to write and how to structure code to conform to this pattern is what it's all about. In this article we will take a look at building a small app in Node.js following a TDD pattern.Read More…
  • Code
    JavaScript & AJAX
    JavaScript ObjectsCover
    In JavaScript, objects are king: Almost everything is an object or acts like an object. Understand objects and you will understand JavaScript. So let's examine the creation of objects in JavaScript.Read More…
  • Code
    PHP
    How to Accept Payments With StripeCode
    Processing credit cards is unfortunately far more difficult than we might hope, as developers. Given that it’s such a common task, is it really necessary that we jump through countless hoops (surrounded by fire, of course) for the sole purpose of processing a payment? Merchants? Gateways? SSL? Security? Very quickly, a seemingly simple operation can become an overwhelmingly confusing and, more importantly, dangerous task. Any time that you find yourself handling a user’s sensitive data, you better be on your toes. Read More…
  • Code
    jQuery
    The State of jQuery in 2013Code
    A long time ago, in a galaxy far, far away, JavaScript was a hated language. In fact, “hated” is an understatement; JavaScript was a despised language. Consequently, developers generally treated it as such, only tipping their toes into the JavaScript waters when they needed to sprinkle a bit of flair into their applications. Some form validation here, an image slider there. Despite the fact that there is a whole lot of good in the JavaScript language, due to widespread ignorance, few took the time to properly learn it.Read More…
  • Code
    Tools
    Your Obedient Assistant: YeomanCode
    One thing is certain: times sure have changed. Not too long ago, front-end development, though not simple, was manageable. Learn HTML, a bit of CSS, and you’re on your way. These days, however, for lack of better words, there are far more variables to juggle. Preprocessors, performance tuning, testing, image optimization, and minification represent but just a few of the key factors that the modern day front-end developer must keep in mind.Read More…