Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jason chan
jason chan
31,009 Points

Can someone walk me through this es6 code?

'use strict'

var invoice = {
  number: 123,
  process: function() {
    return () => console.log(this.number);
  }

};
var newInvoice = {
  number: 456
}
invoice.process().bind(newInvoice)();

So someone walk me through this.

1 Answer

Steven Parker
Steven Parker
229,732 Points

:point_right: This code does something rather silly. Here's the rundown:

'use strict'

This just means that variables must be explicitly declared. Globals will not be created by default.

var invoice = {
  number: 123,
  process: function() {
    return () => console.log(this.number);
  }
};

This creates an object named invoice, with a property named number (set to the value 123) and a method named process. The process method returns an anonymous function which will write the value of invoice.number to the log.

var newInvoice = {
  number: 456
}

This creates an object named newInvoice, with a property named number (set to the value 456).

invoice.process().bind(newInvoice)();

Now we get to the silly part.

Here, invoice.process() returns that anonymous function, and .bind creates a new function that will use newinvoice as its "this" (instead of invoice). The final set of parentheses cause the new function to be invoked.

What makes this silly is that the function returned by invoice.process() has already resolved "this" when it was created and no longer cares what "this" refers to. So this whole line is equivalent to "(invoice.process())()" which itself is equivalent to "console.log(invoice.number)".

Does it make sense now? And where did you find this?