0

I'm trying to understand the difference between regular javascript functions and arrow function. I have implemented code on js bin to see the outcome.

The issue is, I have a normal function and an arrow function as methods inside an object. I'm calling them being in the window scope. The first function call is working fine as I have expected. But in the second one, I use the bind method to bind 'john' object to the arrow function. Altho I use bind, it always takes the scope of the window object. Why is that?

this.table = 'Window table';
this.room = 'Window room';


let john = {
  room: 'johns room',
  table : 'johns table',

  cleanTable(){
    console.log(`cleaning ${this.table}`);
  },
  cleanRoom : () =>{
    console.log(`cleaning ${this.room}`);
  }

}

john.cleanTable();  
john.cleanRoom.bind(john)();

######### output ##########

"cleaning johns table"
"cleaning Window room"


I want both of them to log the same thing which is "cleaning johns table". How can I achieve that?

dmcshehan
  • 1,109
  • 7
  • 14
  • There is no `this` in arrow functions. `this` refers to parent context instead. – 31piy Apr 04 '19 at 07:02
  • 1
    https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions – Vladimir Bogomolov Apr 04 '19 at 07:02
  • Aside the duplicate, don't assign properties to `window` using `this`, it's very error prone. Use `window` instead. Also, please get familiar with [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) before use. – Teemu Apr 04 '19 at 07:05

1 Answers1

0

The simplest is to remove the use of arrow function because it changes the context of the scopes:

this.table = 'Window table';
this.room = 'Window room';


let john = {
  room: 'johns room',
  table : 'johns table',

  cleanTable(){
    console.log(`cleaning ${this.table}`);
  },
  cleanRoom(){
    console.log(`cleaning ${this.room}`);
  }

}

john.cleanTable();  
john.cleanRoom.bind(john)();

If you still want to use the arrow function then pass that object as a parameter and access the property inside the function:

this.table = 'Window table';
this.room = 'Window room';


let john = {
  room: 'johns room',
  table : 'johns table',

  cleanTable(){
    console.log(`cleaning ${this.table}`);
  },
  cleanRoom : (obj) =>{
    console.log(`cleaning ${obj.room}`);
  }

}

john.cleanTable();  
john.cleanRoom(john);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • So basically it means that we cant bind to arrow functions? and does arrow functions always refer to window scope? – dmcshehan Apr 04 '19 at 07:08
  • @dmcshehan it is always a good practice to pass the object as a parameter instead of passing the reference through bind. Check the second example. – Ankit Agarwal Apr 04 '19 at 07:09