SlideShare a Scribd company logo
1 of 69
Download to read offline
Responsible JavaScript
    Refresh NYC — January 2010




                                 1
Where should I get started?
 •   Globals          •   switch () {...}

 •   Namespaces       •   Equality

 •   Prototypes
                      •   $

 •   Factories

 •   this

 •   Incrementing &
     Decrementing


                                            2
Globals



          http://www.lovemikeg.com/blog/2010/01/19/responsible-javascript-globals/
                                                                                 3
Globals have a bad
reputation.


                     4
Where possible, just
avoid them.


                       5
(function () {

  var printMe;

  printMe = document.getElementById(‘print-me’);
  printMe.addEventListener(‘click’, function () {
    window.print();
    return false;
  }, false);

})();




                                                    6
In all other cases,
simply don’t pollute.


                        7
Rules for Responsible Globals


Namespace everything.
Only one global per library.
Only one global per application.




                                   8
Good libraries...


When choosing a library, choose a responsible
one.
   •   jQuery w/compatibility mode is great

   •   YUI is also a great choice




                                                9
Good applications...

Keep it simple: each app gets a global
In most cases, a site == an app
In other cases, a page == an app
   •   searchResults

   •   userProfile

   •   shoppingCart


                                         10
Namespaces



       http://www.lovemikeg.com/blog/2010/01/20/responsible-javascript-namespaces/
                                                                                 11
Namespaces are a
really good idea.


                    12
jQuery.ajax(…)



                 13
Namespaces can get
out of control. Fast.


                        14
com.foo.utils.appManager
  .myApp.widgets
  .contactForm.validate();




                             15
Responsible Namespaces

Use a namespace creator function
Segregate application namespaces from library
namespaces
Organize libraries into component groups
Organize applications into functional groups



                                                16
This might seem like a good
idea…


      var myNS = { … };



   …until you have multiple
     modules in myNS.
                              17
How do you do this reliably?


  myNS.myModule = { … };




                               18
How do you do this reliably?


var myNS = window.myNS || {};
myNS.myModule = {};




                                19
This is a better idea:


   foo.namespace(‘myNS.myModule’);




                                     20
Applications vs. Libraries

Applications are living, breathing structures
which must be accepting to change both
internally and externally.
Libraries are shared dependencies and must be
be organized in a stable structure so as to
minimize the need for change at all.



                                                21
In other words...

You application will be a self-contained entity
which is made up of lots of smaller
components.
   •   Don’t be strict and rigid with your app
       namespaces.

   •   References to other apps are common, keep app
       namespaces shallow.



                                                       22
Prototypes



      http://www.lovemikeg.com/blog/2010/01/21/responsible-javascript-prototype-modification/
                                                                                          23
Prototypes are
powerful.
Really powerful.


                   24
“With great power there must
also come… great responsibility!”
  — Amazing Fantasy #15 (The first Spider-Man story)




                                                      25
“Yeah, but I want convenience.”

Array.prototype.each = function (callback) {
    for (var i = 0, l = this.length; i < l; i++) {
        callback(this[i], i);
    }
};




                                                     26
Think it through…


Is it proper to cast your dependencies on the
language itself?
How/Where is this documented? Is it obvious
to your team?
Are there any other unintended consequences?



                                                27
How many members in foo?
Object.prototype.count = function () {
    var count = 0;
    for (var i in this) count++;
    return count;
};

console.log(
    {'foo':12345}.count()
);




                                         28
Go ahead. Say it.


“But you should be using Object.hasOwnProperty.”
   •   Yeah but does anyone actually do that?

   •   Do you feel comfortable assuming that all future
       developers on your project will know that?




                                                          29
A better option is to
simply extend.


                        30
var MyArray = function () {};
MyArray.prototype = new Array;




                                 31
Factories



            http://www.lovemikeg.com/blog/2010/01/22/responsible-javascript-using-factories/
                                                                                          32
Factories are your
friends.


                     33
Factories manage complexity.


…and anything that reduces complexity should
be considered a best practice right?
Factories can also:
   •   Make your code safer

   •   Make your code faster




                                               34
Factories are a safety measure.

 var Person = function (name, location) {
     this.name = name;
     this.location = location;
 };

 var mike = new Person('Mike G.', 'NYC');
 var alex = Person('Alex H.', 'NYC'); // oops!




                                                 35
Constructors are simply
broken.

Forgetting the new keyword can be disastrous.
Best case scenario, a few globals spill out.
Worst case scenario, your app stops working.




                                                36
Problem solved.

Person.factory = function (name, location) {
  return new Person(name, location);
}

var mike = new Person.factory('Mike G.', 'NYC');
var alex = Person.factory('Alex H.', 'NYC');




                                                   37
this


       http://www.lovemikeg.com/blog/2010/01/23/responsible-javascript-using-this/
                                                                                 38
this  has an identity
crisis.


                        39
var foo = {
  ‘bar’ : 12345,

     ‘getBar’ : function () {
        return this.bar;
     },

     ‘onclickCallback’ : function () {
        window.open(this.href);
        return false;
     },

     ‘wtf’ : function () {
       return {
          ‘hello’ : ‘world’,
          ‘sayHi’ : function () {
            return this.hello;
          }
       };
     }
};

                                         40
this is ambiguous

It refers to the object in which its defined.
Unless:
   •   It’s copied (referenced) to another object

   •   It’s used as an event handler (sometimes).

   •   You .call or .apply it.




                                                    41
Best practices

Know your namespace. Be explicit.
Fix your events.You can never be too sure.
Keep your event handlers in a separate object.
Document all irregularities (including event
handlers).



                                                 42
Incrementing &
Decrementing


                 43
++ and -- have a bad
reputation… to some.


                       44
“The ++ (increment) and -- (decrement) operators
have been known to contribute to bad code by
encouraging excessive trickiness. They are second only
to faulty architecture in enabling to viruses and other
security menaces.”

                             —Douglas Crockford
                               http://www.jslint.com/lint.html#inc




                                                                     45
Trickiness like...
var a = 1;
var b = 2;
var c = 3;

console.log(a++ + b == c);
console.log(a + ++b == c);
console.log(a + + + b == c);

console.log(a, b, c);




                               46
Suggestions


Don’t write tricky code like that.
   •   Probably your best bet ;)
Don’t use incrementors/decrementors
   •   There’s nothing wrong with +=   1




                                           47
switch () {...}



                  48
switch can break if
you don’t break.


                      49
function dateSuffix(date) {
    switch (date){
        case (1) : case (21) : case (31):
            dt = "st";
            break;

        case (2) : case (22):
            dt = "nd";
            break;

        case (3) : case (23):
            dt = "rd";
            break;

        default: dt = "th";
    }

    return date + suffix;
}



                                            50
… is the same as…



                    51
function betterDateSuffix (date) {
    if (date === 1 || date === 21 || date === 31) {
        return date + 'st';
    }
    else if (date === 2 || date === 22) {
        return date + 'nd';
    }
    else if (date === 3 || date === 23) {
        return date + rd;
    }
    else {
        return date + 'th';
    }

    return date + suffix;
}




                                                      52
and …



        53
function yetAnotherDateSuffix   (date) {
    var suffixMap = {
        'st' : (date === 1 ||   date === 21 || date === 31),
        'nd' : (date === 2 ||   date === 22),
        'rd' : (date === 3 ||   date === 23),
        'th' : true
    };

    for (var suffix in suffixMap) {
        if (suffixMap[suffix]) {
            return date + suffix;
        }
    }
}




                                                               54
Which is better?

Depends on your team’s coding standards.
I suggest:
   •   The one which is easiest to understand.

   •   The one which is easiest to change.



(I like the third option, personally.)


                                                 55
Equality



           56
Equality isn’t as easy as
you think.


                            57
Take your best guess
console.log(false   ==   -1);
console.log(false   ==   -0);
console.log(false   ==   0);
console.log(false   ==   []);
console.log(false   ==   "");
console.log(false   ==   "0");
console.log(false   ==   null);
console.log(false   ==   undefined);
console.log(false   ==   null);




                                       58
Take your best guess
console.log(false   ==   -1);          //   false
console.log(false   ==   -0);          //   true
console.log(false   ==   0);           //   true
console.log(false   ==   []);          //   true
console.log(false   ==   "");          //   true
console.log(false   ==   "0");         //   true
console.log(false   ==   null);        //   false
console.log(false   ==   undefined);   //   false
console.log(false   ==   null);        //   false




                                                    59
Just use === or !==


Your code will be less ambiguous
Your code will run faster
   •   No need to convert types




                                   60
$



    61
Developers love $.



                     62
The problem, is that everyone
loves $.

Brought to you by Prototype
Made famous by jQuery


But what happens if you include jQuery and
Prototype on the same page?



                                             63
The Specs say...



“$ is reserved for implementations”
   •   Whatever that means.




                                      64
Fact: $ is perfectly valid.



                              65
“Just don’t do that.”


Yeah. Easier said than done.
   •   Try talking your client its better to rewrite the
       widget written in another library

   •   They like their $$ too.




                                                           66
Just don’t be irresponsible.


Give your devs a choice to use it or not
Never write applications that assume $
Always assume control over $




                                           67
There is hope.

jQuery has compatability mode.
   •   Please use it.

   •   Develop your apps as if you’re writing a plugin…
       var myApp = (function ($) {
         // Your code goes here.
       })(window.jQuery);


YUI is a nice choice too ;)


                                                          68
Thank you.
mikeg@lovemikeg.com




                      69

More Related Content

What's hot

原创 读《大话设计模式》---外观模式(Facade) 收藏
原创 读《大话设计模式》---外观模式(Facade) 收藏原创 读《大话设计模式》---外观模式(Facade) 收藏
原创 读《大话设计模式》---外观模式(Facade) 收藏wensheng wei
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingTakashi Yoshinaga
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploitsPriyanka Aash
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCJohnKennedy
 
20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzleComputer Science Club
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEAndrey Karpov
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
20170415 當julia遇上資料科學
20170415 當julia遇上資料科學20170415 當julia遇上資料科學
20170415 當julia遇上資料科學岳華 杜
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryVincent Pradeilles
 
Common Intermediate Language (.NET) by Example
Common Intermediate Language (.NET) by ExampleCommon Intermediate Language (.NET) by Example
Common Intermediate Language (.NET) by ExampleGanesh Samarthyam
 
Streamy, Pipy, Analyticy
Streamy, Pipy, AnalyticyStreamy, Pipy, Analyticy
Streamy, Pipy, Analyticydarach
 

What's hot (20)

原创 读《大话设计模式》---外观模式(Facade) 收藏
原创 读《大话设计模式》---外观模式(Facade) 收藏原创 读《大话设计模式》---外观模式(Facade) 收藏
原创 读《大话设计模式》---外观模式(Facade) 收藏
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial Mapping
 
7494609
74946097494609
7494609
 
Lath
LathLath
Lath
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveC
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
 
20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle
 
JavaTalks: OOD principles
JavaTalks: OOD principlesJavaTalks: OOD principles
JavaTalks: OOD principles
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
20170415 當julia遇上資料科學
20170415 當julia遇上資料科學20170415 當julia遇上資料科學
20170415 當julia遇上資料科學
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Common Intermediate Language (.NET) by Example
Common Intermediate Language (.NET) by ExampleCommon Intermediate Language (.NET) by Example
Common Intermediate Language (.NET) by Example
 
Streamy, Pipy, Analyticy
Streamy, Pipy, AnalyticyStreamy, Pipy, Analyticy
Streamy, Pipy, Analyticy
 

Similar to Responsible JavaScript

How to really obfuscate your pdf malware
How to really obfuscate   your pdf malwareHow to really obfuscate   your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merklebmerkle
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesEdgar Gonzalez
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesMarakana Inc.
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011Juan Gomez
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataCodemotion Tel Aviv
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Paul Houle
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Paul Houle
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patternsPascal Larocque
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad WoodOrtus Solutions, Corp
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015jbandi
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
Fight with Metaspace OOM
Fight with Metaspace OOMFight with Metaspace OOM
Fight with Metaspace OOMLeon Chen
 

Similar to Responsible JavaScript (20)

Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
How to really obfuscate your pdf malware
How to really obfuscate   your pdf malwareHow to really obfuscate   your pdf malware
How to really obfuscate your pdf malware
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malware
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and Techniques
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad Wood
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Fight with Metaspace OOM
Fight with Metaspace OOMFight with Metaspace OOM
Fight with Metaspace OOM
 

More from Michael Girouard

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerMichael Girouard
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsMichael Girouard
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: EventsMichael Girouard
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataMichael Girouard
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetMichael Girouard
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java ScriptMichael Girouard
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script ColorMichael Girouard
 

More from Michael Girouard (17)

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent Worker
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Ajax for PHP Developers
Ajax for PHP DevelopersAjax for PHP Developers
Ajax for PHP Developers
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script Applications
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: Events
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With Data
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet Wet
 
Its More Than Just Markup
Its More Than Just MarkupIts More Than Just Markup
Its More Than Just Markup
 
Web Standards Evangelism
Web Standards EvangelismWeb Standards Evangelism
Web Standards Evangelism
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
A Look At Flex And Php
A Look At Flex And PhpA Look At Flex And Php
A Look At Flex And Php
 
Baking Cakes With Php
Baking Cakes With PhpBaking Cakes With Php
Baking Cakes With Php
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java Script
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script Color
 

Recently uploaded

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Responsible JavaScript

  • 1. Responsible JavaScript Refresh NYC — January 2010 1
  • 2. Where should I get started? • Globals • switch () {...} • Namespaces • Equality • Prototypes • $ • Factories • this • Incrementing & Decrementing 2
  • 3. Globals http://www.lovemikeg.com/blog/2010/01/19/responsible-javascript-globals/ 3
  • 4. Globals have a bad reputation. 4
  • 6. (function () { var printMe; printMe = document.getElementById(‘print-me’); printMe.addEventListener(‘click’, function () { window.print(); return false; }, false); })(); 6
  • 7. In all other cases, simply don’t pollute. 7
  • 8. Rules for Responsible Globals Namespace everything. Only one global per library. Only one global per application. 8
  • 9. Good libraries... When choosing a library, choose a responsible one. • jQuery w/compatibility mode is great • YUI is also a great choice 9
  • 10. Good applications... Keep it simple: each app gets a global In most cases, a site == an app In other cases, a page == an app • searchResults • userProfile • shoppingCart 10
  • 11. Namespaces http://www.lovemikeg.com/blog/2010/01/20/responsible-javascript-namespaces/ 11
  • 12. Namespaces are a really good idea. 12
  • 14. Namespaces can get out of control. Fast. 14
  • 15. com.foo.utils.appManager .myApp.widgets .contactForm.validate(); 15
  • 16. Responsible Namespaces Use a namespace creator function Segregate application namespaces from library namespaces Organize libraries into component groups Organize applications into functional groups 16
  • 17. This might seem like a good idea… var myNS = { … }; …until you have multiple modules in myNS. 17
  • 18. How do you do this reliably? myNS.myModule = { … }; 18
  • 19. How do you do this reliably? var myNS = window.myNS || {}; myNS.myModule = {}; 19
  • 20. This is a better idea: foo.namespace(‘myNS.myModule’); 20
  • 21. Applications vs. Libraries Applications are living, breathing structures which must be accepting to change both internally and externally. Libraries are shared dependencies and must be be organized in a stable structure so as to minimize the need for change at all. 21
  • 22. In other words... You application will be a self-contained entity which is made up of lots of smaller components. • Don’t be strict and rigid with your app namespaces. • References to other apps are common, keep app namespaces shallow. 22
  • 23. Prototypes http://www.lovemikeg.com/blog/2010/01/21/responsible-javascript-prototype-modification/ 23
  • 25. “With great power there must also come… great responsibility!” — Amazing Fantasy #15 (The first Spider-Man story) 25
  • 26. “Yeah, but I want convenience.” Array.prototype.each = function (callback) { for (var i = 0, l = this.length; i < l; i++) { callback(this[i], i); } }; 26
  • 27. Think it through… Is it proper to cast your dependencies on the language itself? How/Where is this documented? Is it obvious to your team? Are there any other unintended consequences? 27
  • 28. How many members in foo? Object.prototype.count = function () { var count = 0; for (var i in this) count++; return count; }; console.log( {'foo':12345}.count() ); 28
  • 29. Go ahead. Say it. “But you should be using Object.hasOwnProperty.” • Yeah but does anyone actually do that? • Do you feel comfortable assuming that all future developers on your project will know that? 29
  • 30. A better option is to simply extend. 30
  • 31. var MyArray = function () {}; MyArray.prototype = new Array; 31
  • 32. Factories http://www.lovemikeg.com/blog/2010/01/22/responsible-javascript-using-factories/ 32
  • 34. Factories manage complexity. …and anything that reduces complexity should be considered a best practice right? Factories can also: • Make your code safer • Make your code faster 34
  • 35. Factories are a safety measure. var Person = function (name, location) { this.name = name; this.location = location; }; var mike = new Person('Mike G.', 'NYC'); var alex = Person('Alex H.', 'NYC'); // oops! 35
  • 36. Constructors are simply broken. Forgetting the new keyword can be disastrous. Best case scenario, a few globals spill out. Worst case scenario, your app stops working. 36
  • 37. Problem solved. Person.factory = function (name, location) { return new Person(name, location); } var mike = new Person.factory('Mike G.', 'NYC'); var alex = Person.factory('Alex H.', 'NYC'); 37
  • 38. this http://www.lovemikeg.com/blog/2010/01/23/responsible-javascript-using-this/ 38
  • 39. this has an identity crisis. 39
  • 40. var foo = { ‘bar’ : 12345, ‘getBar’ : function () { return this.bar; }, ‘onclickCallback’ : function () { window.open(this.href); return false; }, ‘wtf’ : function () { return { ‘hello’ : ‘world’, ‘sayHi’ : function () { return this.hello; } }; } }; 40
  • 41. this is ambiguous It refers to the object in which its defined. Unless: • It’s copied (referenced) to another object • It’s used as an event handler (sometimes). • You .call or .apply it. 41
  • 42. Best practices Know your namespace. Be explicit. Fix your events.You can never be too sure. Keep your event handlers in a separate object. Document all irregularities (including event handlers). 42
  • 44. ++ and -- have a bad reputation… to some. 44
  • 45. “The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces.” —Douglas Crockford http://www.jslint.com/lint.html#inc 45
  • 46. Trickiness like... var a = 1; var b = 2; var c = 3; console.log(a++ + b == c); console.log(a + ++b == c); console.log(a + + + b == c); console.log(a, b, c); 46
  • 47. Suggestions Don’t write tricky code like that. • Probably your best bet ;) Don’t use incrementors/decrementors • There’s nothing wrong with += 1 47
  • 49. switch can break if you don’t break. 49
  • 50. function dateSuffix(date) { switch (date){ case (1) : case (21) : case (31): dt = "st"; break; case (2) : case (22): dt = "nd"; break; case (3) : case (23): dt = "rd"; break; default: dt = "th"; } return date + suffix; } 50
  • 51. … is the same as… 51
  • 52. function betterDateSuffix (date) { if (date === 1 || date === 21 || date === 31) { return date + 'st'; } else if (date === 2 || date === 22) { return date + 'nd'; } else if (date === 3 || date === 23) { return date + rd; } else { return date + 'th'; } return date + suffix; } 52
  • 53. and … 53
  • 54. function yetAnotherDateSuffix (date) { var suffixMap = { 'st' : (date === 1 || date === 21 || date === 31), 'nd' : (date === 2 || date === 22), 'rd' : (date === 3 || date === 23), 'th' : true }; for (var suffix in suffixMap) { if (suffixMap[suffix]) { return date + suffix; } } } 54
  • 55. Which is better? Depends on your team’s coding standards. I suggest: • The one which is easiest to understand. • The one which is easiest to change. (I like the third option, personally.) 55
  • 56. Equality 56
  • 57. Equality isn’t as easy as you think. 57
  • 58. Take your best guess console.log(false == -1); console.log(false == -0); console.log(false == 0); console.log(false == []); console.log(false == ""); console.log(false == "0"); console.log(false == null); console.log(false == undefined); console.log(false == null); 58
  • 59. Take your best guess console.log(false == -1); // false console.log(false == -0); // true console.log(false == 0); // true console.log(false == []); // true console.log(false == ""); // true console.log(false == "0"); // true console.log(false == null); // false console.log(false == undefined); // false console.log(false == null); // false 59
  • 60. Just use === or !== Your code will be less ambiguous Your code will run faster • No need to convert types 60
  • 61. $ 61
  • 63. The problem, is that everyone loves $. Brought to you by Prototype Made famous by jQuery But what happens if you include jQuery and Prototype on the same page? 63
  • 64. The Specs say... “$ is reserved for implementations” • Whatever that means. 64
  • 65. Fact: $ is perfectly valid. 65
  • 66. “Just don’t do that.” Yeah. Easier said than done. • Try talking your client its better to rewrite the widget written in another library • They like their $$ too. 66
  • 67. Just don’t be irresponsible. Give your devs a choice to use it or not Never write applications that assume $ Always assume control over $ 67
  • 68. There is hope. jQuery has compatability mode. • Please use it. • Develop your apps as if you’re writing a plugin… var myApp = (function ($) { // Your code goes here. })(window.jQuery); YUI is a nice choice too ;) 68