Skip to content

Instantly share code, notes, and snippets.

@angus-c
Last active December 24, 2015 13:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angus-c/6804360 to your computer and use it in GitHub Desktop.
Save angus-c/6804360 to your computer and use it in GitHub Desktop.
// Arrow functions would have been useful for defining concise formulae to be invoked in
// the context of other objects.
// For example here's an object describing a piece of rope. It includes a method which
// returns the area enclosed by the rope.
// Since the enclosed area will vary according to the shape of the rope, the area method
// accepts a formula for calculating the area based on a specified shape.
// However with fat arrows, the context is static and tight-bound so 'this' is wrong and
// 'call' is useless
var pieceOfRope = function(length) {
return {
length: length,
// argument fn defines the area for a given shape
area: function(fn) {return fn.call(this)}
}
}
var myRope = pieceOfRope(6);
var areaOfCircle = myRope.area(()=>this.length*this.length/(Math.PI*4)); // reference error
var areaOfSquare = myRope.area(()=>this.length*this.length/16; // reference error
/****************** // *******************/
// Using thin arrow (which didn't make ES6) 'this' is dynamic and loose-bound so all is good
var pieceOfRope = function(length) {
return {
length: length,
//argument fn defines area for a given shape
area: function(fn) {return fn.call(this)}
}
}
var rope = pieceOfRope(6);
var areaOfCircle = myRope.area(()->this.length*this.length/(Math.PI*4)); //2.86
var areaOfSquare = myRope.area(()->this.length*this.length/16; //2.25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment