Skip to content

Instantly share code, notes, and snippets.

@heygema
Created November 22, 2021 09:35
Show Gist options
  • Save heygema/697e8d4464fef913479c71370fa6e221 to your computer and use it in GitHub Desktop.
Save heygema/697e8d4464fef913479c71370fa6e221 to your computer and use it in GitHub Desktop.
JS this.

title: Js this tags: #programming link: topics: [[Javascript MOC]]


implicit Binding

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

explicit Binding

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();

new Binding

const Animal = function(name, type) {
  this.name = name;
  this.type = type;
}

let omnivore = new Animal("Jane", "Omnivore")

window Binding

/*
@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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment