View on GitHub

marymafa.github.io


layout: post title: Bing date: 2018-03-09 —

Bind method

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Binding functions

Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same. The only exception is the new operator which always return a new context.

To create a bounded function out of the regular function, the bind method is used. bind method takes context to which you want to bind your function as a first argument. The rest of arguments are arguments that will be always passed to such function. It returns a bounded function as a result.

React.createClass

In the oldest component class syntax called React.createClass binding problem is non-existent. That is because React.createClass performs auto-binding under the hood. All methods you define in an object passed to React.createClass will be automatically bound to the component instance. That means you can always use setState, access props, and state and so on from these methods.

This may seem cool, but that means under the hood something magical happened which is not under your control. While it may be perfectly acceptable in 99% of cases, it limits your ability to arbitrary set context - which can be a big issue in more sophisticated codebases.

Why do we bind “this” to the function?

To retain object instance when the function is going to be passed. Certainly, it must be semantically correct for the function to expect such object. The most common case is to bind this when passing object method. Remember.This should be retained when used in the function. This is used for an internal matter, data which, is not dynamic, doesn’t depend on function caller, usually already defined when the function is passed away.