About JavaScript bind method - javascript

reference code segment
this.localizationChanged = this.localizationChanged.bind(this);
Who can tell me why to write like that?

Who can tell me why to write like that?
localizationChanged is used as event handler:
LocalizationStore.addChangeListener(this.localizationChanged);`
If the handler was not bound to the component instance, this would not refer to the component instance and it wouldn't be possible to call the setState method of the component (this.setState(...)).

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.
from MDN.

If you are trying to access this in localizationChanged function you bind this.
However in ES2015 you don't require this.You can use arrow operator :
localizationChanged =()=>{
console.log(this);
}

Related

Need of a call(), apply() and bind() method

I have read lot of theory regarding call(), apply() and bind().
I am not able to understand if we can call method directly why we need call() , apply() or bind()?
Can somebody explain in laymen terms and little in terms of JavaScript?
That's the flexibility offered by Javascript, an object and it's method don't have to be coupled with each other.
Given following object 'a' with a member method 'play'
var a = { play: function (content) { console.log("what is this:", this, content)} }
Use
a.play('Hello')
Is equivalent to
a.play.call(a, 'Hello')
As for your question why need the second way 'call'. Because 'call' gives you a way to call something else instead of 'this', which is 'a' in the example above, so you can do:
a.play.call(document, 'Hello')
About 'apply', it's just another version of 'call', which needs you to pass arguments as an array instead of comma separated parameters. To use apply, you do:
a.play.apply(a, ['Hello'])
As for 'bind', it is to link a function with a 'this' object at first, then get a returned callable object, which you can either call with the rest arguments directly, or pass it into anything else to be called later.
A typical 'bind' use case is React component's event handler. To define an event handler to be passed into a component. You need to use 'bind' in a React class component like this:
handleClick = this.handleClick.bind(this)
Then, in render function:
<Button onClick={this.handleClick} />
Check https://reactjs.org/docs/handling-events.html for the full information.

React Questions

Am I wrong if I explain the provided example like this :
once the component loads, the first button will be clicked automatically because this.handleClick1 was called by adding the bracket.
If you click the second button, there will be an error because you are using an es5 function and the "this" keyword behaves differently in an ES5 function compared with the arrow function or ES6 function. In ES5 function, the "this" keyword refers directly to the object that contains it and in this case the object that contains it is the which is an object and so there is an error because the button object does not contain a handleClick1 property. To fix this problem, you have to either use an ES6 function to declare the handleClick1 function or if you must use the ES5 function then you have to bind the function to the class
The first button is not clicked immediately. You are calling the handler function immediately instead of assigning it as the handler.
Arrow functions and .bind() act similar in that they statically bind this for that function.
However, React.Component won't statically bind methods to itself. If you (properly) set a button onClick to a component method, the context will change. To fix this somewhat unexpected behavior you will need to use arrow functions or .bind() in the constructor.
Keep in mind that if you were to call handleClick1() from inside your component (as you do when improperly setting the first button handler) this will be what you expect it to be. Thats just how this works.
Here's a sandbox for anyone interested: https://codesandbox.io/s/react-playground-forked-nimby?file=/index.js

Extracting a method in Javascript

I learned that if I wanted to extract a method from this example.
var jane={
name:'jane',
describe:function(){
return 'Person named '+this.name;
}
};
I cannot do as follows.
var func =jane.describe;
func();
As it does not work, why does this not work? Also I was told the solution is as follows
var func =jane.describe.bind(jane);
func();
I do not understand this, what is this "bind" property of functions and why is "jane" passed into the bind property?
This will not work because the context of this changes. When you use bind, you pass the object jane to bind so then when you call describe and it uses this it references jane.
As per the documentation:
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.
Reading Material
bind

bind this is optional in class if no constructor?

I have below class, but I'm confused by the bind this here. The class don't have a constructor and super(), why did he need to do bind this on setAll method? I removed the bind this, the application still work and no error.
class PushScheduleActions {
/**
* Request all API
*/
fetchAll(params) {
return dispatch => {
dispatch(params);
PushScheduleApi.getAll(params)
.then(this.setAll.bind(this));//why use bind this here?
.catch(this.setError.bind(this));
}
}
setAll(data) {
return data;
}
}
There is no relation between constructor, super and bind.
What bind does?
it returns a new function with the context user passed.
In your case, PushScheduleApi success case you are passing a new setAll function which is returned by bind method.
since your setAll function doesn't use context, you don't need to pass the context.
dispatch is an arrow function, so context is inherited. So you dont need bind method. you can simply use this.setAll
The class don't have a constructor and super()
That's completely irrelevant.
why did he need to do bind this on setAll method?
The method only needs to be bound if
it uses thisand
this should refer to what this refers to inside fetchAll (likely an instance of PushScheduleActions).
Since setAll doesn't reference this, there is no reason to bind.
However, the whole setAll method is unnecessary. The code would work exactly the same without .then(this.setAll.bind(this)). That makes me think that PushScheduleActions is supposed to be subclassed and child classes are supposed to overwrite setAll. Now, the child class' setAll might use this and expect it to refer to the instance. Since the parent class (PushScheduleActions) can't know that, binding the method is safer since it will ensure that child class implementations of setAll will work regardless if they use this or not.
The bind() function creates a new bound function (BF). A BF is an exotic function object (a term from ECMAScript 2015) that wraps the original function object. Calling a BF generally, results in the execution of its wrapped function.
For more detail follow this link i hope it will help you a lot to understand to bind() method
Use of the JavaScript 'bind' method

How to set a function along with its arguments as a callback?

Consider the following code snippet:
$scope.delete=function(){
foo('x',3);
};
Is there any cleaner way to write this? I mean when the callback function consist of one line with call another function? (clearly, I can not write it as $scope.delete=foo('x',3))
You can use Function.prototype.bind()
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.
For example:
$scope.delete = foo.bind(null, 'x', 3);
You can use bind as follows:
$scope.delete=foo.bind(this, 'x',3);
Where the first argument is the function context. That is, the value this will assume when the function is executed.
From the MDN documentation
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.

Categories

Resources