ES6 Arrow functions and correct using of bind(this)

function Desciples(firstname, attributes) {
  this.firstname = firstname;
  this.attributes = attributes;
  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    });
  };
}

let desciple1 = new Desciples("John", [
  "Author of Gospel of John ",
  "Author of Reveleations",
  "Desicple that Jesus loved"
]);

desciple1.listAttributes();

retuns

"undefined did Author of Gospel of John "
"undefined did Author of Reveleations"
"undefined did Desicple that Jesus loved"

But if we change it to

this.listAttributes = function() {
    return this.attributes.map(attrib => {
      console.log(this.firstname + " did " + attrib);
    });


"John did Author of Gospel of John "
"John did Author of Reveleations"
"John did Desicple that Jesus loved"

We can also create local variable to the function and assign this to it

 this.listAttributes = function() {
    self = this;
    return this.attributes.map(function (attrib)  {
      console.log(self.firstname + " did " + attrib);
    });
  };

We can also use the BIND on the function like:

  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    }.bind(this));
  };

Or the MAP has a second paramenter and we can pass this there that will also work

  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    },this);
  };

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image