SlideShare ist ein Scribd-Unternehmen logo
1 von 110
Downloaden Sie, um offline zu lesen
The many facets of code reuse in
           JavaScript




                          Leonardo Borges
                          @leonardo_borges
                          http://www.leonardoborges.com
                          http://www.thoughtworks.com
Highly opinionated
    talk ahead
JavaScript is all about
       Objects
Not classes
Not access modifiers
Just Objects
Objects
• An unordered collection of properties
• Arrays are Objects
• Functions are Objects
• Regular Expressions are Objects
                   ...you catch my drift
Ok, I lied.
There’s more to JavaScript than just
             Objects
The Prototype
The Prototype
            Object


          - prototype
          - __proto__
The Prototype
            Object


          - prototype
          - __proto__
The Prototype
 myObject           Object


- prototype       - prototype
- __proto__       - __proto__
The Prototype
 myObject           Object


- prototype       - prototype
- __proto__       - __proto__
The Prototype
   myObject           Object


  - prototype       - prototype
  - __proto__       - __proto__




undefined
The Prototype
   myObject           Object


  - prototype       - prototype
  - __proto__       - __proto__




undefined         function Empty() {}
But how do you create Objects?
Object Literals
 var person = {
     firstName: "Leonardo",
     lastName: "Borges",
     age: 29
 };
Object.create
• Specified by the ECMAScript 5th edition
• Modern browsers such as Chrome and Firefox already implement it
Object.create
• Specified by the ECMAScript 5th edition
• Modern browsers such as Chrome and Firefox already implement it

          var anotherPerson = Object.create(person, {
              age: { value: 50 }
          });
          anotherPerson.age; //50
Object.create
if (typeof Object.create !== 'function') {
    Object.create = function(o) {
        var F = function() {};
        F.prototype = o;
        return new F();
    };
}

var anotherPerson = Object.create(person);
Functions




                            f(x)
• First class objects
• Linked to Function.prototype
• Can be used as constructors
Functions
             Function


            - prototype
            - __proto__
Functions
             Function


            - prototype
            - __proto__




      function Empty() {}
Functions
myFunction                 Function


- prototype               - prototype
- __proto__               - __proto__




                    function Empty() {}
Functions
myFunction                 Function


- prototype               - prototype
- __proto__               - __proto__




                    function Empty() {}
Functions
myFunction                 Function


- prototype               - prototype
- __proto__               - __proto__




                    function Empty() {}
Function calls
                  Implicit arguments:

• this, the current object
• arguments, an array containing all values passed
into the function call
function f(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(this);
    console.log(arguments);
}
f(1, 2, 3);
function f(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(this);
    console.log(arguments);
}
f(1, 2, 3);

//   1
//   2
//   3
//   DOMWindow
//   [1, 2, 3]
function f(a, b, c) {
              console.log(a);
              console.log(b);
              console.log(c);
              console.log(this);
              console.log(arguments);
          }
          f(1, 2, 3);

          //   1
          //   2
          //   3
          //   DOMWindow
          //   [1, 2, 3]

The value of this changes depending on how the
               function is called.
Calling functions: as methods
 var person = {
     firstName: "Leonardo",
     lastName: "Borges",
     fullName: function() {
         return this.firstName + " " + this.lastName;
     }
 };

 person.fullName();
Calling functions: as methods
 var person = {
     firstName: "Leonardo",
     lastName: "Borges",
     fullName: function() {
         return this.firstName + " " + this.lastName;
     }
 };

 person.fullName();


                                        this is bound to person
Calling functions: as, err, functions
    this.firstName = "Leo";
    this.lastName = "Borges";

    function fullName() {
        return this.firstName + " " + this.lastName;
    }

    fullName(); //Leo Borges
    this; //DOMWindow
Calling functions: as, err, functions
    this.firstName = "Leo";
    this.lastName = "Borges";

    function fullName() {
        return this.firstName + " " + this.lastName;
    }

    fullName(); //Leo Borges
    this; //DOMWindow

                                       this is bound to the
                                        global object
Calling functions: using apply
  Allows the value of this to be changed upon calling:
Calling functions: using apply
  Allows the value of this to be changed upon calling:
         var anotherPerson = {
             firstName: "Johnny",
             lastName: "Cash"
         };

         person.fullName.apply(anotherPerson);
         //Johnny Cash
Calling functions: using apply
  Allows the value of this to be changed upon calling:
         var anotherPerson = {
             firstName: "Johnny",
             lastName: "Cash"
         };

         person.fullName.apply(anotherPerson);
         //Johnny Cash




                                          this is bound to
                                          anotherPerson
Calling functions: constructors

         //constructor function
         var F = function() {};

         var obj = new F();
What does new do?

Creates a new object, obj
                                      var obj = {};

Assigns F’s public prototype to the   obj.__proto__ === F.prototype// true
obj internal prototype
                                      this === obj// true

Binds this to obj
Don’t use new
Don’t use new

• No built-in checks to prevent constructors from
being called as regular functions
• If you forget new, this will be bound to the
global object
But I want to
new workaround
//constructor function
var F = function() {
    if (!(this instanceof F)) {
        return new F();
    }
};

var obj = new F();
var obj = F();
//both previous statements are now equivalent
new workaround
//constructor function
var F = function() {
    if (!(this instanceof F)) {
        return new F();
    }
};

var obj = new F();
var obj = F();
//both previous statements are now equivalent




 You can see how cumbersome this can get
Closures
var Person = function(name) {
    this.name = name;
    return {
        getName: function() {
            return this.name;
        }
    };
};
var leo = new Person("leo");
leo.getName();
Closures
var Person = function(name) {
    this.name = name;
    return {
        getName: function() {
            return this.name;
        }
    };
};
var leo = new Person("leo");
leo.getName();



                    Can you guess what this line returns?
undefined
Closures
var Person = function(name) {
    this.name = name;
    return {
        getName: function() {
            return this.name;
        }
    };
};
var leo = new Person("leo");
leo.getName();
Closures
                           var Person = function(name) {
                               this.name = name;
                               return {
                                   getName: function() {
                                       return this.name;
Bound to the person   object
                                   }
                               };
                           };
                           var leo = new Person("leo");
                           leo.getName();
Closures
                           var Person = function(name) {
                               this.name = name;
                               return {
                                   getName: function() {
                                       return this.name;
Bound to the person   object
                                   }
                               };
                           };
                           var leo = new Person("leo"); Bound   to the object literal
                           leo.getName();
Closures

Allows a function to access variables outside it’s scope
Closures
var Person = function(name) {
    this.name = name;
    var that = this;
    return {
        getName: function() {
            return that.name;
        }
    };
};

var leo = new Person("leo");
leo.getName(); // “leo”
Closures
                               var Person = function(name) {
                                   this.name = name;
                                   var that = this;



                               {
                                   return {
    getName is now a                   getName: function() {
closure: it closes over that               return that.name;
                                       }
                                   };
                               };

                               var leo = new Person("leo");
                               leo.getName(); // “leo”
Sharing behaviour
Pseudoclassical inheritance
   //constructor function
   var Aircraft = function(name){
       this.name = name;
   };
   Aircraft.prototype.getName = function() {
       return this.name;
   }
   Aircraft.prototype.fly = function() {
       return this.name + ": Flying...";
   }
Pseudoclassical inheritance
   //constructor function
   var Aircraft = function(name){
       this.name = name;
   };
   Aircraft.prototype.getName = function() {
       return this.name;
   }
   Aircraft.prototype.fly = function() {
       return this.name + ": Flying...";
   }


   var cirrus = new Aircraft("Cirrus SR22"); 
   cirrus.getName(); //"Cirrus SR22"
   cirrus.fly(); //"Cirrus SR22: Flying..."
Pseudoclassical inheritance
  var Jet = function(name){
      this.name = name;
  };
  Jet.prototype = new Aircraft();
  Jet.prototype.fly = function() {
      return this.name + ": Flying a jet...";
  }
Pseudoclassical inheritance
  var Jet = function(name){
      this.name = name;
  };
  Jet.prototype = new Aircraft();
  Jet.prototype.fly = function() {
      return this.name + ": Flying a jet...";
  }


  var boeing = new Jet("Boeing 747");
  boeing.getName(); //"Boeing 747"
  boeing.fly(); //"Boeing 747: Flying a jet..."
Prototypal inheritance

• Objects inherit directly from other objects
• Sometimes referred to as differential inheritance
Prototypal inheritance
var myAircraft = {
    name: "Cirrus SR22",
    getName: function() {
        return this.name;
    },
    fly: function() {
        return this.name + ": Flying...";
    }
};

myAircraft.getName(); //"Cirrus SR22"
myAircraft.fly(); //"Cirrus SR22: Flying..."
Prototypal inheritance
var myJet = Object.create(myAircraft);
myJet.name = "Boeing 747";
myJet.fly = function() {
    return this.name + ": Flying a jet...";
}

myJet.getName(); //"Boeing 747"
myJet.fly(); //"Boeing 747: Flying a jet..."
Weaknesses
• Lack of private members - all properties are public
• No easy access to super
• In the pseudoclassical pattern, forgetting new will break
your code
Weaknesses
• Lack of private members - all properties are public
• No easy access to super
• In the pseudoclassical pattern, forgetting new will break
your code

                     Strengths
• Using the prototype is the fastest way to create
objects when compared to closures
• In practice it will only matter if you’re creating
thousands of objects
Functional inheritance
var aircraft = function(spec) {
    var that = {};
    that.getName = function() {
        return spec.name;
    };
    that.fly = function() {
        return spec.name + ": Flying...";
    };
    return that;
};
Functional inheritance
                                            Members declared
var aircraft = function(spec) {              here are private
    var that = {};
    that.getName = function() {
        return spec.name;
    };
    that.fly = function() {
        return spec.name + ": Flying...";
    };
    return that;
};
Functional inheritance
var myAircraft = aircraft({ name: "Cirrus SR22" });
myAircraft.getName(); //"Cirrus SR22"
myAircraft.fly(); //"Cirrus SR22: Flying..."
Functional inheritance
var myAircraft = aircraft({ name: "Cirrus SR22" });
myAircraft.getName(); //"Cirrus SR22"
myAircraft.fly(); //"Cirrus SR22: Flying..."




myAircraft.that; //undefined
Functional inheritance
var jet = function(spec) {
    var that = aircraft(spec);
    that.fly = function() {
        return spec.name + ": Flying a jet...";
    };
    return that;
};
Functional inheritance                            that is now an
var jet = function(spec) {
                                                     aircraft
    var that = aircraft(spec);
    that.fly = function() {
        return spec.name + ": Flying a jet...";
    };
    return that;
};
Functional inheritance                            that is now an
var jet = function(spec) {
                                                     aircraft
    var that = aircraft(spec);
    that.fly = function() {
        return spec.name + ": Flying a jet...";
    };
    return that;
};



var myJet = jet({ name: "Boeing 747" });   
myJet.getName(); //"Boeing 747"
myJet.fly(); //"Boeing 747: Flying a jet..."
But I want to reuse my fly function
Implementing super

Object.prototype.super = function(fName) {
    var that = this;
    var f = that[fName];

    return function() {
        return f.apply(that, arguments);
    };
};
Revisiting jet
var jet = function(spec) {
    var that = aircraft(spec),
        superFly = that.super("fly");
    that.fly = function() {
        return superFly() + "a frickin' jet!";
    };
    return that;
};

var myJet = jet({
    name: "Boeing 747"
});
myJet.fly(); //"Boeing 747: Flying...a frickin' jet!"
Functional inheritance
           Weaknesses
• Consumes more memory: every object created allocates
new function objects as necessary
• In practice it will only matter if you’re creating thousands
of objects
Functional inheritance
           Weaknesses
• Consumes more memory: every object created allocates
new function objects as necessary
• In practice it will only matter if you’re creating thousands
of objects

                     Strengths
 • It’s conceptually simpler than pseudoclassical inheritance
 • Provides true private members
 • Provides a way of working with super (albeit verbose)
 • Avoids the new workaround since new isn’t used at all
Both Prototypal and Functional patterns
            are powerful
Both Prototypal and Functional patterns
            are powerful

   I’d avoid the pseudoclassical path
But wait! Inheritance isn’t the only way
           to share behaviour
An alternative to inheritance:
           Mixins
   var utils = {};
   utils.enumerable = {
       reduce: function(acc, f) {
           for (var i = 0; i < this.length; i++) {
               acc = f(acc, this[i]);
           }
           return acc;
       }
   };
An alternative to inheritance:
           Mixins       Sitck it into a module so
                                              as to avoid clobbering
    var utils = {};                           the global namespace
    utils.enumerable = {
        reduce: function(acc, f) {
            for (var i = 0; i < this.length; i++) {
                acc = f(acc, this[i]);
            }
            return acc;
        }
    };
Mixins - implementing extends
    utils.extends = function(dest,source) {
        for (var prop in source) {
            if (source.hasOwnProperty(prop)) {
                dest[prop] = source[prop];
            }
        }
    };
Mixins
extending Array.prototype
   utils.extends(Array.prototype, utils.enumerable);
Mixins
extending Array.prototype
   utils.extends(Array.prototype, utils.enumerable);


        [1,2,3].reduce(0, function(acc,item) {
            acc += item;
            return acc;
        }); // 6
Going apeshit
        functional
Partial function application
Partial function application
  var sum = function(a, b) {
      return a + b;
  };
Partial function application
  var sum = function(a, b) {
      return a + b;
  };


  var inc = utils.partial(sum, 1);
Partial function application
  var sum = function(a, b) {
      return a + b;
  };


  var inc = utils.partial(sum, 1);


  inc(8); //9
Partial function application
Partial function application
  var times = function(a, b) {
      return a * b;
  }
Partial function application
  var times = function(a, b) {
      return a * b;
  }


  var double = utils.partial(times, 2);
Partial function application
  var times = function(a, b) {
      return a * b;
  }


  var double = utils.partial(times, 2);


  double(10); //20
Partial function application

utils.partial = function(f) {
    var sourceArgs = Array.prototype.slice.apply(arguments, [1]);
    return function() {
        var actualArgs = Array.prototype.concat.apply(sourceArgs, arguments);
        return f.apply(null, actualArgs);
    };
};
Partial function application

utils.partial = function(f) {
    var sourceArgs = Array.prototype.slice.apply(arguments, [1]);
    return function() {
        var actualArgs = Array.prototype.concat.apply(sourceArgs, arguments);
        return f.apply(null, actualArgs);
    };
};

                                                                                a h
                                                                          ye
                                                                    *   k
                                                                f *
Function composition:
  Reversing a string
Function composition
utils.split = function(str) {
    return String.prototype.split.apply(str, [""]);
};

utils.reverse = function(array) {
    return Array.prototype.reverse.apply(array);
};

utils.join = function(array) {
    return Array.prototype.join.apply(array, [""]);
};
Function composition

var reverseStr = utils.comp(utils.split, utils.reverse, utils.join);
Function composition

var reverseStr = utils.comp(utils.split, utils.reverse, utils.join);

reverseStr("leonardo"); //odranoel
Function composition
utils.comp = function() {
    var functions = Array.prototype.slice.apply(arguments, [0]);
    return function() {
        var result = functions.reduce(arguments, function(r, f) {
            return [f.apply(null, r)]
        });
        return result[0];

    };
};
Function composition
utils.comp = function() {
    var functions = Array.prototype.slice.apply(arguments, [0]);
    return function() {
        var result = functions.reduce(arguments, function(r, f) {
            return [f.apply(null, r)]
        });
        return result[0];

    };
                                                                          a h
};

                                                                     ye
                                                               *   k
                                                           f *
Thankfully              implements
 these - and much more - for us!
Bottom line
Bottom line

• Embrace JavaScript’s true prototypal nature
Bottom line

• Embrace JavaScript’s true prototypal nature
• Use mixins, prototypal and functional inheritance to dispense with
classes and the new keyword
Bottom line

• Embrace JavaScript’s true prototypal nature
• Use mixins, prototypal and functional inheritance to dispense with
classes and the new keyword
• Use higher order functions, partial application and function
composition as elegant alternatives to promote code reuse
Bottom line

• Embrace JavaScript’s true prototypal nature
• Use mixins, prototypal and functional inheritance to dispense with
classes and the new keyword
• Use higher order functions, partial application and function
composition as elegant alternatives to promote code reuse
• Above all, understand each pattern’s strengths and weaknesses
Thanks!

Questions?
        Leonardo Borges
       @leonardo_borges
http://www.leonardoborges.com
 http://www.thoughtworks.com
References
• JavaScript: the Good Parts (http://amzn.to/zY04ci)
• Test-Driven JavaScript Development (http://amzn.to/yHCexS)
• Secrets of the JavaScript Ninja (http://bit.ly/wOS4x2)
• Closures wiki article (http://bit.ly/xF2OfP)
• Underscore.js - functional programming for JS (http://bit.ly/JLkIbm)
• Presentation source code (http://bit.ly/HU8kL6)


                                                             Leonardo Borges
                                                             @leonardo_borges
                                                             http://www.leonardoborges.com
                                                             http://www.thoughtworks.com

Weitere ähnliche Inhalte

Was ist angesagt?

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJosé Paumard
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin KingUnFroMage
 

Was ist angesagt? (20)

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin King
 

Andere mochten auch

Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
SEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 GoogleSEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 GoogleNguyễn Trọng Thơ
 

Andere mochten auch (9)

Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
SEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 GoogleSEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 Google
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 

Ähnlich wie The many facets of code reuse in JavaScript

JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course yoavrubin
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02plutoone TestTwo
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptShah Jalal
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkuiKhou Suylong
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritancepedro.carvalho
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...it-people
 

Ähnlich wie The many facets of code reuse in JavaScript (20)

Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Prototype
PrototypePrototype
Prototype
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
 
Javascript
JavascriptJavascript
Javascript
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 

Mehr von Leonardo Borges

Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Leonardo Borges
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Leonardo Borges
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library designLeonardo Borges
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptLeonardo Borges
 
Programação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoProgramação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoLeonardo Borges
 
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Leonardo Borges
 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.asyncLeonardo Borges
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptLeonardo Borges
 
Clojure/West 2013 in 30 mins
Clojure/West 2013 in 30 minsClojure/West 2013 in 30 mins
Clojure/West 2013 in 30 minsLeonardo Borges
 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Leonardo Borges
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 
Heroku addons development - Nov 2011
Heroku addons development - Nov 2011Heroku addons development - Nov 2011
Heroku addons development - Nov 2011Leonardo Borges
 
Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Leonardo Borges
 
Clouds Against the Floods
Clouds Against the FloodsClouds Against the Floods
Clouds Against the FloodsLeonardo Borges
 

Mehr von Leonardo Borges (20)

Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Programação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncronoProgramação functional reativa: lidando com código assíncrono
Programação functional reativa: lidando com código assíncrono
 
Monads in Clojure
Monads in ClojureMonads in Clojure
Monads in Clojure
 
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.async
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
Clojure/West 2013 in 30 mins
Clojure/West 2013 in 30 minsClojure/West 2013 in 30 mins
Clojure/West 2013 in 30 mins
 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Heroku addons development - Nov 2011
Heroku addons development - Nov 2011Heroku addons development - Nov 2011
Heroku addons development - Nov 2011
 
Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011)
 
Clouds Against the Floods
Clouds Against the FloodsClouds Against the Floods
Clouds Against the Floods
 
Arel in Rails 3
Arel in Rails 3Arel in Rails 3
Arel in Rails 3
 
Testing with Spring
Testing with SpringTesting with Spring
Testing with Spring
 

Kürzlich hochgeladen

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Kürzlich hochgeladen (20)

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

The many facets of code reuse in JavaScript

  • 1. The many facets of code reuse in JavaScript Leonardo Borges @leonardo_borges http://www.leonardoborges.com http://www.thoughtworks.com
  • 2. Highly opinionated talk ahead
  • 3. JavaScript is all about Objects
  • 7. Objects • An unordered collection of properties • Arrays are Objects • Functions are Objects • Regular Expressions are Objects ...you catch my drift
  • 9. There’s more to JavaScript than just Objects
  • 11. The Prototype Object - prototype - __proto__
  • 12. The Prototype Object - prototype - __proto__
  • 13. The Prototype myObject Object - prototype - prototype - __proto__ - __proto__
  • 14. The Prototype myObject Object - prototype - prototype - __proto__ - __proto__
  • 15. The Prototype myObject Object - prototype - prototype - __proto__ - __proto__ undefined
  • 16. The Prototype myObject Object - prototype - prototype - __proto__ - __proto__ undefined function Empty() {}
  • 17. But how do you create Objects?
  • 18. Object Literals var person = {     firstName: "Leonardo",     lastName: "Borges",     age: 29 };
  • 19. Object.create • Specified by the ECMAScript 5th edition • Modern browsers such as Chrome and Firefox already implement it
  • 20. Object.create • Specified by the ECMAScript 5th edition • Modern browsers such as Chrome and Firefox already implement it var anotherPerson = Object.create(person, {     age: { value: 50 } }); anotherPerson.age; //50
  • 21. Object.create if (typeof Object.create !== 'function') {     Object.create = function(o) {         var F = function() {};         F.prototype = o;         return new F();     }; } var anotherPerson = Object.create(person);
  • 22. Functions f(x) • First class objects • Linked to Function.prototype • Can be used as constructors
  • 23. Functions Function - prototype - __proto__
  • 24. Functions Function - prototype - __proto__ function Empty() {}
  • 25. Functions myFunction Function - prototype - prototype - __proto__ - __proto__ function Empty() {}
  • 26. Functions myFunction Function - prototype - prototype - __proto__ - __proto__ function Empty() {}
  • 27. Functions myFunction Function - prototype - prototype - __proto__ - __proto__ function Empty() {}
  • 28. Function calls Implicit arguments: • this, the current object • arguments, an array containing all values passed into the function call
  • 29. function f(a, b, c) {     console.log(a);     console.log(b);     console.log(c);     console.log(this);     console.log(arguments); } f(1, 2, 3);
  • 30. function f(a, b, c) {     console.log(a);     console.log(b);     console.log(c);     console.log(this);     console.log(arguments); } f(1, 2, 3); // 1 // 2 // 3 // DOMWindow // [1, 2, 3]
  • 31. function f(a, b, c) {     console.log(a);     console.log(b);     console.log(c);     console.log(this);     console.log(arguments); } f(1, 2, 3); // 1 // 2 // 3 // DOMWindow // [1, 2, 3] The value of this changes depending on how the function is called.
  • 32. Calling functions: as methods var person = {     firstName: "Leonardo",     lastName: "Borges",     fullName: function() {         return this.firstName + " " + this.lastName;     } }; person.fullName();
  • 33. Calling functions: as methods var person = {     firstName: "Leonardo",     lastName: "Borges",     fullName: function() {         return this.firstName + " " + this.lastName;     } }; person.fullName(); this is bound to person
  • 34. Calling functions: as, err, functions this.firstName = "Leo"; this.lastName = "Borges"; function fullName() {     return this.firstName + " " + this.lastName; } fullName(); //Leo Borges this; //DOMWindow
  • 35. Calling functions: as, err, functions this.firstName = "Leo"; this.lastName = "Borges"; function fullName() {     return this.firstName + " " + this.lastName; } fullName(); //Leo Borges this; //DOMWindow this is bound to the global object
  • 36. Calling functions: using apply Allows the value of this to be changed upon calling:
  • 37. Calling functions: using apply Allows the value of this to be changed upon calling: var anotherPerson = {     firstName: "Johnny",     lastName: "Cash" }; person.fullName.apply(anotherPerson); //Johnny Cash
  • 38. Calling functions: using apply Allows the value of this to be changed upon calling: var anotherPerson = {     firstName: "Johnny",     lastName: "Cash" }; person.fullName.apply(anotherPerson); //Johnny Cash this is bound to anotherPerson
  • 39. Calling functions: constructors //constructor function var F = function() {}; var obj = new F();
  • 40. What does new do? Creates a new object, obj var obj = {}; Assigns F’s public prototype to the obj.__proto__ === F.prototype// true obj internal prototype this === obj// true Binds this to obj
  • 42. Don’t use new • No built-in checks to prevent constructors from being called as regular functions • If you forget new, this will be bound to the global object
  • 44. new workaround //constructor function var F = function() {     if (!(this instanceof F)) {         return new F();     } }; var obj = new F(); var obj = F(); //both previous statements are now equivalent
  • 45. new workaround //constructor function var F = function() {     if (!(this instanceof F)) {         return new F();     } }; var obj = new F(); var obj = F(); //both previous statements are now equivalent You can see how cumbersome this can get
  • 46. Closures var Person = function(name) {     this.name = name;     return {         getName: function() {             return this.name;         }     }; }; var leo = new Person("leo"); leo.getName();
  • 47. Closures var Person = function(name) {     this.name = name;     return {         getName: function() {             return this.name;         }     }; }; var leo = new Person("leo"); leo.getName(); Can you guess what this line returns?
  • 49.
  • 50. Closures var Person = function(name) {     this.name = name;     return {         getName: function() {             return this.name;         }     }; }; var leo = new Person("leo"); leo.getName();
  • 51. Closures var Person = function(name) {     this.name = name;     return {         getName: function() {             return this.name; Bound to the person object         }     }; }; var leo = new Person("leo"); leo.getName();
  • 52. Closures var Person = function(name) {     this.name = name;     return {         getName: function() {             return this.name; Bound to the person object         }     }; }; var leo = new Person("leo"); Bound to the object literal leo.getName();
  • 53. Closures Allows a function to access variables outside it’s scope
  • 54. Closures var Person = function(name) {     this.name = name;     var that = this;     return {         getName: function() {             return that.name;         }     }; }; var leo = new Person("leo"); leo.getName(); // “leo”
  • 55. Closures var Person = function(name) {     this.name = name;     var that = this; {     return { getName is now a         getName: function() { closure: it closes over that             return that.name;         }     }; }; var leo = new Person("leo"); leo.getName(); // “leo”
  • 57. Pseudoclassical inheritance //constructor function var Aircraft = function(name){     this.name = name; }; Aircraft.prototype.getName = function() {     return this.name; } Aircraft.prototype.fly = function() {     return this.name + ": Flying..."; }
  • 58. Pseudoclassical inheritance //constructor function var Aircraft = function(name){     this.name = name; }; Aircraft.prototype.getName = function() {     return this.name; } Aircraft.prototype.fly = function() {     return this.name + ": Flying..."; } var cirrus = new Aircraft("Cirrus SR22");  cirrus.getName(); //"Cirrus SR22" cirrus.fly(); //"Cirrus SR22: Flying..."
  • 59. Pseudoclassical inheritance var Jet = function(name){     this.name = name; }; Jet.prototype = new Aircraft(); Jet.prototype.fly = function() {     return this.name + ": Flying a jet..."; }
  • 60. Pseudoclassical inheritance var Jet = function(name){     this.name = name; }; Jet.prototype = new Aircraft(); Jet.prototype.fly = function() {     return this.name + ": Flying a jet..."; } var boeing = new Jet("Boeing 747"); boeing.getName(); //"Boeing 747" boeing.fly(); //"Boeing 747: Flying a jet..."
  • 61. Prototypal inheritance • Objects inherit directly from other objects • Sometimes referred to as differential inheritance
  • 62. Prototypal inheritance var myAircraft = {     name: "Cirrus SR22",     getName: function() {         return this.name;     },     fly: function() {         return this.name + ": Flying...";     } }; myAircraft.getName(); //"Cirrus SR22" myAircraft.fly(); //"Cirrus SR22: Flying..."
  • 63. Prototypal inheritance var myJet = Object.create(myAircraft); myJet.name = "Boeing 747"; myJet.fly = function() {     return this.name + ": Flying a jet..."; } myJet.getName(); //"Boeing 747" myJet.fly(); //"Boeing 747: Flying a jet..."
  • 64. Weaknesses • Lack of private members - all properties are public • No easy access to super • In the pseudoclassical pattern, forgetting new will break your code
  • 65. Weaknesses • Lack of private members - all properties are public • No easy access to super • In the pseudoclassical pattern, forgetting new will break your code Strengths • Using the prototype is the fastest way to create objects when compared to closures • In practice it will only matter if you’re creating thousands of objects
  • 66. Functional inheritance var aircraft = function(spec) {     var that = {};     that.getName = function() {         return spec.name;     };     that.fly = function() {         return spec.name + ": Flying...";     };     return that; };
  • 67. Functional inheritance Members declared var aircraft = function(spec) { here are private     var that = {};     that.getName = function() {         return spec.name;     };     that.fly = function() {         return spec.name + ": Flying...";     };     return that; };
  • 68. Functional inheritance var myAircraft = aircraft({ name: "Cirrus SR22" }); myAircraft.getName(); //"Cirrus SR22" myAircraft.fly(); //"Cirrus SR22: Flying..."
  • 69. Functional inheritance var myAircraft = aircraft({ name: "Cirrus SR22" }); myAircraft.getName(); //"Cirrus SR22" myAircraft.fly(); //"Cirrus SR22: Flying..." myAircraft.that; //undefined
  • 70. Functional inheritance var jet = function(spec) {     var that = aircraft(spec);     that.fly = function() {         return spec.name + ": Flying a jet...";     };     return that; };
  • 71. Functional inheritance that is now an var jet = function(spec) { aircraft     var that = aircraft(spec);     that.fly = function() {         return spec.name + ": Flying a jet...";     };     return that; };
  • 72. Functional inheritance that is now an var jet = function(spec) { aircraft     var that = aircraft(spec);     that.fly = function() {         return spec.name + ": Flying a jet...";     };     return that; }; var myJet = jet({ name: "Boeing 747" });    myJet.getName(); //"Boeing 747" myJet.fly(); //"Boeing 747: Flying a jet..."
  • 73. But I want to reuse my fly function
  • 74. Implementing super Object.prototype.super = function(fName) {     var that = this;     var f = that[fName];     return function() {         return f.apply(that, arguments);     }; };
  • 75. Revisiting jet var jet = function(spec) {     var that = aircraft(spec),         superFly = that.super("fly");     that.fly = function() {         return superFly() + "a frickin' jet!";     };     return that; }; var myJet = jet({     name: "Boeing 747" }); myJet.fly(); //"Boeing 747: Flying...a frickin' jet!"
  • 76. Functional inheritance Weaknesses • Consumes more memory: every object created allocates new function objects as necessary • In practice it will only matter if you’re creating thousands of objects
  • 77. Functional inheritance Weaknesses • Consumes more memory: every object created allocates new function objects as necessary • In practice it will only matter if you’re creating thousands of objects Strengths • It’s conceptually simpler than pseudoclassical inheritance • Provides true private members • Provides a way of working with super (albeit verbose) • Avoids the new workaround since new isn’t used at all
  • 78. Both Prototypal and Functional patterns are powerful
  • 79. Both Prototypal and Functional patterns are powerful I’d avoid the pseudoclassical path
  • 80. But wait! Inheritance isn’t the only way to share behaviour
  • 81. An alternative to inheritance: Mixins var utils = {}; utils.enumerable = {     reduce: function(acc, f) {         for (var i = 0; i < this.length; i++) {             acc = f(acc, this[i]);         }         return acc;     } };
  • 82. An alternative to inheritance: Mixins Sitck it into a module so as to avoid clobbering var utils = {}; the global namespace utils.enumerable = {     reduce: function(acc, f) {         for (var i = 0; i < this.length; i++) {             acc = f(acc, this[i]);         }         return acc;     } };
  • 83. Mixins - implementing extends utils.extends = function(dest,source) {     for (var prop in source) {         if (source.hasOwnProperty(prop)) {             dest[prop] = source[prop];         }     } };
  • 84. Mixins extending Array.prototype utils.extends(Array.prototype, utils.enumerable);
  • 85. Mixins extending Array.prototype utils.extends(Array.prototype, utils.enumerable); [1,2,3].reduce(0, function(acc,item) {     acc += item;     return acc; }); // 6
  • 86. Going apeshit functional
  • 88. Partial function application var sum = function(a, b) {     return a + b; };
  • 89. Partial function application var sum = function(a, b) {     return a + b; }; var inc = utils.partial(sum, 1);
  • 90. Partial function application var sum = function(a, b) {     return a + b; }; var inc = utils.partial(sum, 1); inc(8); //9
  • 92. Partial function application var times = function(a, b) {     return a * b; }
  • 93. Partial function application var times = function(a, b) {     return a * b; } var double = utils.partial(times, 2);
  • 94. Partial function application var times = function(a, b) {     return a * b; } var double = utils.partial(times, 2); double(10); //20
  • 95. Partial function application utils.partial = function(f) {     var sourceArgs = Array.prototype.slice.apply(arguments, [1]);     return function() {         var actualArgs = Array.prototype.concat.apply(sourceArgs, arguments);         return f.apply(null, actualArgs);     }; };
  • 96. Partial function application utils.partial = function(f) {     var sourceArgs = Array.prototype.slice.apply(arguments, [1]);     return function() {         var actualArgs = Array.prototype.concat.apply(sourceArgs, arguments);         return f.apply(null, actualArgs);     }; }; a h ye * k f *
  • 97. Function composition: Reversing a string
  • 98. Function composition utils.split = function(str) {     return String.prototype.split.apply(str, [""]); }; utils.reverse = function(array) {     return Array.prototype.reverse.apply(array); }; utils.join = function(array) {     return Array.prototype.join.apply(array, [""]); };
  • 99. Function composition var reverseStr = utils.comp(utils.split, utils.reverse, utils.join);
  • 100. Function composition var reverseStr = utils.comp(utils.split, utils.reverse, utils.join); reverseStr("leonardo"); //odranoel
  • 101. Function composition utils.comp = function() {     var functions = Array.prototype.slice.apply(arguments, [0]);     return function() {         var result = functions.reduce(arguments, function(r, f) {             return [f.apply(null, r)]         });         return result[0];     }; };
  • 102. Function composition utils.comp = function() {     var functions = Array.prototype.slice.apply(arguments, [0]);     return function() {         var result = functions.reduce(arguments, function(r, f) {             return [f.apply(null, r)]         });         return result[0];     }; a h }; ye * k f *
  • 103. Thankfully implements these - and much more - for us!
  • 105. Bottom line • Embrace JavaScript’s true prototypal nature
  • 106. Bottom line • Embrace JavaScript’s true prototypal nature • Use mixins, prototypal and functional inheritance to dispense with classes and the new keyword
  • 107. Bottom line • Embrace JavaScript’s true prototypal nature • Use mixins, prototypal and functional inheritance to dispense with classes and the new keyword • Use higher order functions, partial application and function composition as elegant alternatives to promote code reuse
  • 108. Bottom line • Embrace JavaScript’s true prototypal nature • Use mixins, prototypal and functional inheritance to dispense with classes and the new keyword • Use higher order functions, partial application and function composition as elegant alternatives to promote code reuse • Above all, understand each pattern’s strengths and weaknesses
  • 109. Thanks! Questions? Leonardo Borges @leonardo_borges http://www.leonardoborges.com http://www.thoughtworks.com
  • 110. References • JavaScript: the Good Parts (http://amzn.to/zY04ci) • Test-Driven JavaScript Development (http://amzn.to/yHCexS) • Secrets of the JavaScript Ninja (http://bit.ly/wOS4x2) • Closures wiki article (http://bit.ly/xF2OfP) • Underscore.js - functional programming for JS (http://bit.ly/JLkIbm) • Presentation source code (http://bit.ly/HU8kL6) Leonardo Borges @leonardo_borges http://www.leonardoborges.com http://www.thoughtworks.com