title: Js this tags: #programming link: topics: [[Javascript MOC]]
a Binding that occurs upon the creation of the object. hint: when you try to look for where is this
refers to, look at the left of the dot (.) when a function is invoked.
const me = {
name: 'X',
sayName: function() {
console.log(this.name);
}
};
// this is the `me`
me.sayName()
but in case of arrow function
() => {}
let you = {name: 'you', sayName: () => {console.log(this.name)}} // undefined
this is because arrow function by default binds this
, to where in scope it was created, in this case if it's in the browser, the window object. if it was this case:
function createYou(name) {this.name=name, this.sayName = () => {console.log(this.name)}}
let you = new createYou("a person");
you.sayName(); // "a person"
but you cannot rebind it anywhere after it was defined
You cannot rebind
this
in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function. source
there are 3 explicit this
Binding
- .apply
- .call
- .bind
example of usage:
.call
const me = {
name: 'Stacey'
}
function hello(address, address2, address3) {
console.log("hello ", this.name, ", ", address, ", " , address2, ", ", address3);
}
hello.call(me, "Hollywood", address2)
.apply same as .call, but we can apply array of args
let addresses = ["Malibu", "California", "New York"]
hello.apply(me, addresses);
.bind
const me = {
name: 'Stacey'
}
function hello(address) {
console.log("hello ", this.name, ", ", address);
}
let newHello = hello.bind(me, 'Hollywood')
neHello();
const Animal = function(name, type) {
this.name = name;
this.type = type;
}
let omnivore = new Animal("Jane", "Omnivore")
/*
@example
if you don't want it to implicitly binds to window object or global. put use strict';
*/
const sayName = function() {
'use strict';
console.log(this.name);
}
const sayName = function() {
console.log(this.name);
}
sayName();