• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JavaScript functional programming

 
Tomasz Prus
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to use Javascript in functional (applicative) programming style? Does it have a facilities fo FP? Propably i'm wrong but some guy said that i should embrace JS as functional language.
[ August 27, 2008: Message edited by: Ulf Dittmer ]
 
Stoyan Stefanov
author
Ranch Hand
Posts: 82
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Short answer: yep

Functions in JavaScript are first-class objects. You have function literals, you can store functions in variables, add/remove their properties and so on. This gives you a great expressive power.



An interesting pattern for code reuse that comes to mind is stealing (or borrowing) methods.

Imagine this object:


Now another object:


Now 'hoho' doesn't have a getName() method but it can borrow it from 'o':



This way getName() is invoked and 'hoho' is bound to 'this' inside getName()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic