Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

jason chan
jason chan
31,008 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
215,956 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?