$❯ CrowderSoup

A website about programming, technology, and life.

Tag: tips

Managing Scope Using Call, Apply, and Bind

by Aaron Crowder on

Call

Calls a function, with the specified arguments passed in

The first argument becomes this, the rest are passed in as regular arguments. Using call allows you to maintain the scope of this accross methods. It works like this:

Here we're using prototypical inheritance to allow us to inheirit properties from Animal in Dog and Cat. Using call allows us to invoke Animal to initialize it's properties while maintaining the correct scope.

Apply

Calls a function, with the specified arguments passed in as an array

Just like call, the first argument becomes this. The rest of the args are passed in as an array.

Bind

Creates a bound function with the same function body as the function it's called on

With bind, we actually get a reference to a new function. The first argument passed to bind becomes this, and the rest are passed as regular arguments. This is especially handy for event handlers.

Wrapping up

These examples are fairly trivial, but they do serve to show that it's possible to manage scope without aliasing this to something like self. In a lot of cases that can actually be pretty confusing. But, as with everything, use what makes sense! This method may or may not work well for you, and that's okay.

JavaScript: Array's with named Properties

by Aaron Crowder on

Adding named properties to arrays in JavaScript can be handy in a few different cases. For instance:

  • You need a nice formatted title / description for a data set. Rather than having multiple objects you can use named properties and get away with only using one.
  • You want to add some functions to an array for whatever reason
  • Lots of other reasons that I can't think of right now!

Basically, this just buys you a nice way to encapsulate all the data you might need, without having to use an object with a nested array, or multiple objects. Maybe your way is more clean or better for this reason or that... I just thought this was neat. :)

Let's get into some code to play around with this. I'm going to use JSFiddle.net for this so you can play with the code yourself.

The reason that this works is because of the way that array.length is updated. In JavaScript, array.length is updated whenever you use a built-in array method (e.g., join, push, unshift, etc). So, when you build an array, all the numerically indexed properties are taken into accound as part of the length.

When you add a named property to the array it doesn't update the length, and therefore you can iterate over an array and only get the numerically indexed items.