Saturday, July 11, 2015

the "fat arrow" operator in ECMAScript 6

The old school self-equals-this way of handing this on as predictable state like so...

function superstructureSentence() {
   var self = this;
   return function(act) {
      var sentence = "The ";
      self.foxyAdjectives.forEach(function(f) {
         sentence = sentence + f + " ";
      });
      sentence = sentence + "fox " + act + "s over the ";
      self.doggishAdjectives.forEach(function(d) {
         sentence = sentence + d + " ";
      });
      alert(sentence + "dog.");
   }
}
var glitz = {
   foxyAdjectives : ["quick", "red"],
   doggishAdjectives : ["lazy", "brown"]
};
var structureSentence = superstructureSentence.call(glitz);
structureSentence("jump");
structureSentence("fuck");

 
 

...may now be approached as follows with the arrow.

function superstructureSentence() {
   return (act) => {
      var sentence = "The ";
      this.foxyAdjectives.forEach(function(f) {
         sentence = sentence + f + " ";
      });
      sentence = sentence + "fox " + act + "s over the ";
      this.doggishAdjectives.forEach(function(d) {
         sentence = sentence + d + " ";
      });
      alert(sentence + "dog.");
   }
}
var glitz = {
   foxyAdjectives : ["quick", "red"],
   doggishAdjectives : ["lazy", "brown"]
};
var structureSentence = superstructureSentence.call(glitz);
structureSentence("jump");
structureSentence("fuck");

 
 

I read about as much in "this & OBJECT PROTOTYPES" by Kyle Simpson! Both of these blobs of code give us two alerts, telling us:

  1. The quick red fox jumps over the lazy brown dog.
  2. The quick red fox fucks over the lazy brown dog.

No comments:

Post a Comment