this
dynamic
The bind
solves a problem caused by the context of JavaScript
, It provides a way to ensure that even decontaminating a function of an object its behavior remains the same, thus ensuring an integrity of the function’s behavior. This is interesting in the case of programação funcional
, where the ideal is terms funções puras
, which they possess as part of their ideology be a function without side effect.
An example of the problem:
function Usuario() {
this._nome = '';
this.setNome = function(nome) {
this._nome = nome;
};
this.getNome = function() {
return this._nome;
};
}
var johnDoe = new Usuario();
johnDoe.setNome('John Doe');
console.log(johnDoe.getNome()); // 'John Doe'
Here we have a simple constructor function that serves to represent the user entity on our system. Note that it does not use bind
, and we’re using the object johnDoe
, the context of the function does not suffer any problem. The problems of not using a bind
(or other solution) in this case only appear when we decouple the function of the object.
var johnDoe = new Usuario();
var setNome = johnDoe.setNome;
setNome('John Doe');
console.log(johnDoe.getNome()); // ''
console.log(window._nome)); // 'John Doe'
When we decouple a function to a variable, the context of the function becomes the global context, then its behavior is totally broken. Note that the problem also occurs when you pass the function as parameter to another function.
var johnDoe = new Usuario();
function popularNome(setNome) {
setNome('John Doe');
}
popularNome(johnDoe.setNome);
console.log(johnDoe.getNome()); // ''
console.log(window._nome)); // 'John Doe'
When we work with events from DOM
, Where we record a function to listen to an event we also have a similar problem, because the context of the function is modified in the call by the event listener. When the function recorded in an event is called, the scope of the function becomes the element that triggered the action. Like the onClick
is an event if the bind
were not done, he would have this problem:
var usuario = {
_nome: '',
setNome: function(event) {
this._nome = event.target.value;
}
};
var elNome = document.getElementById('nome');
// O contexto da função setNome seria
// equivalente ao "elNome"
elNome.addEventListener('keyup', usuario.setNome);
Example of the problem: https://jsfiddle.net/fvenq166/
+1 because of the citation of Class Instance Field
– Gabriel Katakura