Professional Documents
Culture Documents
in Javascript
A few rules determine what the 'this’ keyword is inside a function
Reglas
1. If the new keyword is used when calling the
function, this inside the function is a brand new object.
Si la palabra clave ‘new’ es usada cuando se llama a la
función, el ‘this’ dentro de la función es un nuevo objeto.
function ConstructorExample() {
console.log(this);
this.value = 10;
console.log(this);
}new ConstructorExample();// -> {}
// -> { value: 10 }
const obj = {
value: 'abc',
createArrowFn: function() {
return () => console.log(this);
}
};const arrowFn = obj.createArrowFn();arrowFn(); // -> {
value: 'abc', createArrowFn: ƒ }
Libraries
Libraries will sometimes intentionally bind the value
of this inside their functions. this is bound to the most useful
value for use in the function. jQuery, for example,
binds this to the DOM element triggering an event in the
callback to that event. If a library has an
unexpected this value that doesn’t seem to follow the rules,
check its documentation. It’s likely being bound using bind.
If this (no pun intended) was helpful, please
hit the ❤ and feel free to subscribe and
check out some of my other work.