This can also be defined within a function. So here when I am creating edgyBoy my new Square :) I am able to reference Square attributes via the “this” keyword.
.bind allowing a programmer to redefine “this” adds extra functionality to an object without having to actually add a method to the object itself. Now lets say we are writing some silly chatbot app where you can ask questions. When you have a constructor function you can pass it different objects and the .bind method will allow you to change the “this” keyword to the object being passed.
The constructor function WhatsForDinner does not take any arguments and when console.log(this) we are returning the .window object. However if we use WhatsForDinner.bind() we can pass in an object that will also redefine the “this” keyword.
As you can imagine this setup up can keep a developers code DRY and absent of repeats. Providing methods or attributes in your constructor function and passing object literals will prevent repeated code. You can also even accomplish this functionality with arguably less code by using .call instead of .bind. The .call method actually calls a function with a given this value while the .bind method creates a new function that when called assigns the this keyword to the object passed in. So again .call does not require creating a new function that then needs to be called. 2 less steps! So let’s take a look at this in our what for dinner example.
This approach is a bit on the nose and may not be as efficient when you have to create an object literal every time you use .call. So the smarter work around is to use two constructor methods!
The above code may seem a bit confusing but is a much more effective way to create Meals and use the .call() method for returning a response for WhatsForDinner. The console.log(this) is showing the meal object which is where we are using the .call() method. The response of the meal object is showing up as undefined because both name and ingredients are going to be attributes of a meal and simply passed in.
So that is where I will leave “this” :). Both .bind and .call are very powerful tools and really expand the flexibility of this which in turn opens up a lot of programming doors. Hope you all found this helpful!