Smashing Newsletter

Dealing with this in JavaScript can be tricky. But what if instead of fight against it we could leverage on it to achieve nice stuff like function composition with virtual methods? This is what we are going to explore in this article about one of the potential upcoming JavaScript features: The Bind Operator.

Do you want to discover the next exciting JavaScript features that you didn’t even know you needed? In this article, I will introduce one of these proposals that if accepted may change the way you write code the same way the spread operator did.

However, here’s a small disclaimer: This feature is under development and discussion. The goal here is to add some hype around it and create awareness of the hard work that TC39 is doing to find consensus, fix all the syntax and semantics issues and have it shipped with the next releases of ECMAScript. If you have any concerns, comments or desire to express your support, please go to the TC39 proposals repository, add a star to this feature to show your support, open an issue to voice your concerns and get involved.

But before, I want to ask a simple (but tricky) question:

What isthis?

In ECMAScript, this has a different semantic than this in many other programming languages, where this often refers to the lexical scope. In general, this behaves differently in the global scope, within a function, in non-strict mode and strict mode. Let’s break this behavior down into small examples.

this In The Global Scope

What is the value of this in this example?

console.info(this);

At the global scope, this refers to the global object, like the window in the browser, self on web workers and the module.exports object in NodeJS.

this In The Function Scope

At the function scope, this behaves depending on how the function is called, and this aspect makes it tricky to predict its value. We can understand it better by checking the following examples:

What Is The Value Of this Here?

function foo() {
return this;
}
console.info(this);

Inside a function, this starts to have an interesting behavior since its value depends on how the function is called. In the example above, this still refers to the global scope, with one difference. In NodeJs, this will point to the global object instead of module.exports.

Setting A Value Into this:

Setting a value into this sets the value into the current context. The example above logs the global scope with the property bar with the value baz in the first console.info, but it logs only { bar: ‘baz’ } in the second console.info. It happens because the new operator among other things bounds the value of this to the newly created object.

This Keyword In The Strict Mode

In strict mode, the this variable doesn’t carry the value of the context implicitly, this means if its context isn’t set, the value of this is default to undefined as shown in the following snippet.

To set the context of this in strict mode you can set the function as member of an object, use new operator, Function.prototype.call(), Function.prototype.apply() or Function.prototype.bind() methods for example.

Making this Variable Predictable

At this point, you may realize that the value of this in ECMAScript is quite tricky to predict. To demonstrate the available techniques to make it predictable, I’d like to present the following example that mimics a common use case of this.

In the example above, I created a MeowctComponent, which has only one property paw that points to the button element and one method called meow that should print the paw instance property into the console.

The tricky part is that the meow method is executed only when the button is clicked, and because of that, this has the button tag as context, and since the button tag does not have any paw property, it logs the undefined value into the console. Tricky, isn’t it?

To fix this specific behavior we can leverage on the Function.prototype.bind() method to explicitly bind this to the cat instance, like in the following example:

The method .bind() returns a new permanently bound function to the first given parameter, which is the context. Now, because we bound the cat.meow method to the cat instance, this.paw inside the meow method correctly points to the button element.

As an alternative to the Function.prototype.bind() method, we can use the arrow function to achieve the same result. It keeps the value of the lexical this of the surrounding context and dispenses the need to bind the context explicitly, like in the next example:

Let's suppose for any reason we have this obj object that doesn't extend Object.prototype but we need to check if obj has an x property by using the hasOwnProperty method from Object.prototype. To achieve that, we have to use the call method and explicitly pass obj as the first parameter to make it work as expected, which appears not to be so idiomatic.

Extracting A Method

The second case can be spotted when we need to extract a method from an object like in our MeowctComponent example:

It’s super useful because the developer doesn’t need to download the whole lib to do small stuff, which reduces the amount of imported JavaScript. Besides, it makes those kinds of libs easier to extend.

How To Develop Using Bind Operator

To keep the example simple, let’s suppose we need to create a math module which the developer can chain the operations to form an math expression that, given a number as an entry it could make all calculations into a pipeline. The code to achieve this is simple and could be written as the following.

So far, we demonstrate how create functions to interact with the values, but what about extending the object with virtual methods? We can do new stream compositions mixing built-in methods with custom ones. To demonstrate it, we can compose string methods with custom ones. First, let's check the module with the custom methods with its implementation.

In the example above, you can spot that I extracted two methods from the String.prototype, trim() and padEnd(). Since these methods are extracted, I can use them to compose my stream of methods alongside with my virtual methods capitalize(), doubleSay() and exclamation(). This aspect is what makes bind operator so exciting and promising.

Advantages And Disadvantages Of Bind Operator

As you may realize at this point, there are some aspects that Bind Operator shines. Those are the following:

It covers the only two missing use cases that explicit bind is necessary;

It makes easy to make this variable to be predictable;

It adds a new way to extend functionality by using virtual methods;

It helps to extend built-in objects without extending the prototype chain. Do you remember Smoosh Gate?

In the other side, to compose functions with bind operator you need to rely on this to be bound, that can lead to some issues like in this example:

As it becomes clear in the example above, it’s not possible to compose arrow function with bind operator, since it’s not possible to bind this to an arrow function. Sometimes users don’t want to rely on this to be bound to compose their behavior through a function chain, which could be a problem if you only use bind operator to achieve this.

Another issue that is often said is the possible syntax overload that the bind operator can bring which can be a problem to onboard newcomers to the language. Realizing that a specific operator works in binary and unary form is tricky as well. One possible solution for this is to introduce the binary form to the language separately of the unary form. So once the binary form is integrated to the language, the committee can reassess if the unary form is still necessary. Meanwhile, users can get used to the binary form, and the syntax overload could potentially be mitigated.

Conclusion

Predict the value of this in JavaScript is trick. The language has some rules to explain how the context is assigned to this, but in the daily basis we want to make this value predictable. The Function.prototype.bind() method and arrow functions help us to make the value of this predictable. The bind operator comes to play to cover the two use cases that we still need to explicitly bind this.

The advent of bind operator opens an opportunity to create a new set of function composition via virtual methods, but it can add a syntax overload making difficult to onboard newcomers to the language.

The author of the bind operator is Kevin Smith, and this proposal is in Stage 0. The TC39 is open to feedback. If you like this feature and think that it’s useful, please add a star in the repository, if you have an Idea to solve the issues presented here, if you have another way to shape the syntax or semantics of this features or if you spot another issue with it, please open an issue in the repo and share your thoughts/ideas with the committee.