Mastering this in JavaScript

JavaScript developers—new and experienced—constantly rate the variable this as a major pain of the language. The this variable, which represents a function’s context, plays an important role in everyday JavaScript programming, so understanding how it works is critical. This blog post gives an overview of this and its many quirks and forms. We will lay out the four ways to set a function’s this value, as well as discuss some common use cases and pitfalls.

What is Context?

But first, what is context in the first place? Think of it like this: if a function is a sentence, the context is the sentence’s subject. It represents who or what the function is about. If a function is creating a new user, the context would be the user instance. The way we access a function’s context is through the variable this.

It seems simple, so why is it so hard to understand? Developers routinely get tripped up by this, and that’s largely due to the fact that we’re used to lexical scoping. With lexical scoping, we can see the value of a variable by finding its assignment in earlier code. So when we want to know what usersCount holds, we can just scroll up and find where that variable is set.

Here’s a visual example:

That’s lexical scoping.

The this variable, however, uses dynamic scoping. We have much less exposure to dynamic scoping than we do to lexical scoping, so naturally it’s more difficult to grasp. With dynamic scoping, variables are set depending on how the host function is called. So the value of this is any given function depends entirely on how and where that function was called in the first place.

Intuition and this

Before getting into the nitty gritty, let’s consider what we already know about this. Most anyone who’s written jQuery code has seen an event binding like this:

$('button').on('click', function() {
    $(this).addClass('was_clicked');
    // $(this) refers to the button the was clicked 
});

When that button is clicked, the callback function runs. We access the $(‘button’) that was clicked inside the callback with $(this). It makes intuitive sense that this would represent the button, because that is the natural subject of the callback function.

The Four Ways to Set a Function’s this Value

Without further ado, here are the 4 ways to set a function’s this value:

  1. Call a method on an object, like object.method()
  2. Pass this in with .call() and .apply()
  3. Use new to make this start out empty
  4. Manually bind a this value with .bind()

If none of the above are used, this is the global scope object (i.e. window in a browser). This is a very bad thing and we should always avoid it by using one of the four rules.

Now, let’s dive into each method.

Read More

Five Ruby Methods You Should Be Using

Five Ruby Methods You Should Be Using

There's something magical about the way that Ruby just flows from your fingertips. why once said "Ruby will teach you to express your ideas through a computer." Maybe that's why Ruby has become such a popular choice for modern web development.

Just as in English, there are lots of ways to say the same thing in Ruby. I spend a lot of time reading and nitpicking people's code on Exercism, and I often see exercises solved in a way that could be greatly simplified if the author had only known about a certain Ruby method.

Here's a look at some lesser-known Ruby methods that solve specific types of problem very well.

Read More
Learn about Engine Yard
Try Engine Yard for your Ruby or PHP Apps

Engine Yard Sponsors Bundler

Engine Yard Sponsors Bundler

Open Source is at the heart of what we and our customers do here at Engine Yard. As a company that founded itself in the roots of the Ruby and Rails communities, we always find the best tools to help foster growth when it comes to building the best applications. In that vein, we are proud to announce our sponsorship of Bundler!

In the dark days, adding gems and managing dependencies in a Ruby application was cantankerous at best. Luckily, a few developers saw the need to fix this. Early in its development, Engine Yard employed Yehuda Katz, Carl Lerche, and André Arko to develop Bundler and help all Ruby developers get out of “dependency hell”.

Read More

Taming Asynchronous JavaScript with Async.js

JavaScript is often described as asynchronous, meaning that function calls and operations don’t block the main thread while they execute. This is true in some situations, but JavaScript runs in a single thread, and therefore has lots of synchronous components.

It’s more accurate to say that many function calls in JavaScript can be made asynchronously. Web programming essentials like DOM event handlers and AJAX calls are asynchronous, and because these common tasks make up a great bulk of JavaScript programming, JavaScript itself is often labeled "asynchronous."

When a function runs asynchronously, that means it doesn’t stop subsequent function calls from running while it finishes. Take this example:

var users = [];
$.get(/users, function(data) {
  users = data;
});
renderUsersOnPage(users);

Since $.get() is asynchronous, the next functional call (to render the users) will execute immediately, whether the fetch call has finished or not. This means that our data won’t be available to us when we try to render it, because the earlier call to fetch them from the API is still being executed!

So, the main problem with asynchronous programming is how to call asynchronous functions that depend on each other. How do you ensure function A has finished before calling function B, if you can’t rely on function A blocking until it’s done?

Read More

Introduction to MySQL's Innodb Memcached Interface

Introduction to MySQL's Innodb Memcached Interface

Note: This is part three in our Extending MySQL with PHP's MySQLnd Series

With MySQL 5.6 a memcache-compatible innodb-backed key-value store was added to MySQL.

The InnoDB Memcache Daemon gives you the permanence of innodb for key-value data, that can be accessed via the much faster, optimized memcached protocol — using this will skip the query parser, optimizer and other parts of engine that are unnecessary.

With mysqlnd_memcache, you can transparently route queries to this memcache-compatible interface.

Read More

CHECK OUT OUR CURATED COLLECTIONS

Look through our specially curated posts to get focused, in-depth information on a single topic.