% of dynamic%
this
solves a problem caused by the context of bind
, it provides a way to ensure that even by decoupling a function from an object its behavior remains the same, thus ensuring integrity of the behavior of the function. This is interesting in the case of JavaScript
, where the ideal is programação funcional
terms, which have as part of their ideology a non-collateral function.
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 in our system. Note that it does not use funções puras
, and because we are using the bind
object, the context of the function suffers no problem at all. The problems of not using a johnDoe
(or another solution) in this case only appear when we uncouple the function from 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 uncouple a function for a variable, the context of the function becomes the global context, so its behavior is completely broken. Note that the problem also occurs when you pass the function as a 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 of bind
, where we register a function to listen for an event we also have a similar problem, because the function context is modified in the event listener call. When the function registered in an event is called, the scope of the function becomes the element that triggered the action. Since DOM
is an event, if onClick
was not done, it 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);
Problem example: link