SlideShare a Scribd company logo
JavaScript styles
    and some tips
What you usually see
 around the Internet
function Auction(initialPrice) {
   this.bids = [];
   this.initialPrice = initialPrice;
   this.currentPrice = initialPrice;
}

Auction.prototype.bid = function (amount) {
   this.currentPrice += amount;
   this.bids.push(amount);
};

Action.prototype.history = function () {
   return this.bids.copy();
};

var auction = new Auction(10.0);

auction.bid(9001);
console.log(auction.history());
Pros
Somewhat organized
Kinda looks like a Class
Allows changing behavior
   of existing instances
    through prototype
   (but that's actually a bad thing)
Cons
Where's my scope?
Everything's public
A better approach
function Auction(initialPrice) {
   var currentPrice = initialPrice;
   var bids = [];

    this.bid = function (amount) {
       currentPrice += amount;
       bids.push(amount);
    };

    this.history = function () {
       return bids.copy();
    };
}

var auction = new Auction(10.0);

auction.bid(9001);
console.log(auction.history());
Pros
Everything contained in a
    single Function
Proper scoping
Control over public
     interface
Cons
"this" keyword is scary
        .apply, .call
How to fix?
function Auction(initialPrice) {
   var currentPrice = initialPrice;
   var bids = [];

    var api = {};
    api.bid = function (amount) {
       currentPrice += amount;
       bids.push(amount);
    };
    api.history = function () {
       return bids.copy();
    };

    return api;
}

var auction = new Auction(10.0);

auction.bid(9001);
console.log(auction.history());
Pros
No more "this"
Cons
Memory usage
"prototype" won't work
    (but that's actually good)
Tips
Namespacing
var ove = ove || {};
ove.model = ove.model || {};

ove.model.Auction = function (...) {
   // ...
};

var auction = new ove.model.Action();
There are libraries for that
but it's nice to understand what's happening
Monkey-patching Array,
 Function, and String's
          fine
  don't mess with the DOM though
Function.prototype.curry = function () { ... };

String.prototype.each = function () { ... };

Array.prototype.foldLeft = function () { ... };
Know when you see this?
people = [Person.new(18), Person.new(22), Person.
new(65)];

canDrink = [];
for person in people
    if (person.age > 20)
        canDrink.push(person);
    end
end
Why are you writing your
  Java in my Ruby?
What about this?
class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move()
Why are you writing your
Ruby in my JavaScript?
Moving on
Avoid small magics
<input id="field-id" />
<input id="field-name" />
<input id="field-email" />


function validate(field) {
   var val = $('#field-' + field).val();
   // ...
}

validate('id');
validate('name');
validate('email');
Use the scope
images.each(function (image) {
    var li = $('<li></li>', {
                 'class': 'image',
                 'data-id': image.id()});
    container.append(li);
});

<ul>
   <li class="image" data-id="1"></li>
</ul>

$('li.image', container).click(function () {
    var id = this.attr('data-id');
    view.dialog.openImage(id);
});
images.each(function (image) {
    var li = $('<li></li>')
    li.click(function () {
        view.dialog.openImage(image.id());
    });
    container.append(li);
});
Avoid state
<ul id="cars">
   <li class="car">
       <input type="checkbox">First Car</input>
   </li>
   <li class="car">
       <input type="checkbox">Carman</input>
   </li>
<ul>


var selectedCars = [];
$('#cars .car input').click(function () {
    if (this.checked)
       selectedCars.push(this);
    else
       selectedCars.remove(this);
});
$('#cars .car input:checked');

More Related Content

What's hot (20)

PDF
Oop in java script
Pierre Spring
 
PPTX
ProgrammingwithGOLang
Shishir Dwivedi
 
PPTX
Stop Programming in JavaScript By Luck
sergioafp
 
PDF
Functions
Kamal Acharya
 
PDF
Short intro to ECMAScript
Jussi Pohjolainen
 
PPT
Lecture05
elearning_portal
 
PPTX
Javascript this keyword
Pham Huy Tung
 
PPTX
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
.NET Conf UY
 
PDF
Javascript & Ajax Basics
Richard Paul
 
PPT
C++ tutorial
sikkim manipal university
 
PDF
Improving the java type system
João Loff
 
PPT
C++totural file
halaisumit
 
PPTX
Mca 2nd sem u-4 operator overloading
Rai University
 
PDF
ES2015 workflows
Jarrod Overson
 
TXT
bullismo e scuola primaria
imartini
 
PDF
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Filipe Ximenes
 
PDF
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Fábio Pimentel
 
PDF
Tasks: you gotta know how to run them
Filipe Ximenes
 
PPT
Class ‘increment’
Syed Zaid Irshad
 
PDF
Angular 2.0: Brighter future?
Eugene Zharkov
 
Oop in java script
Pierre Spring
 
ProgrammingwithGOLang
Shishir Dwivedi
 
Stop Programming in JavaScript By Luck
sergioafp
 
Functions
Kamal Acharya
 
Short intro to ECMAScript
Jussi Pohjolainen
 
Lecture05
elearning_portal
 
Javascript this keyword
Pham Huy Tung
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
.NET Conf UY
 
Javascript & Ajax Basics
Richard Paul
 
Improving the java type system
João Loff
 
C++totural file
halaisumit
 
Mca 2nd sem u-4 operator overloading
Rai University
 
ES2015 workflows
Jarrod Overson
 
bullismo e scuola primaria
imartini
 
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Filipe Ximenes
 
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Fábio Pimentel
 
Tasks: you gotta know how to run them
Filipe Ximenes
 
Class ‘increment’
Syed Zaid Irshad
 
Angular 2.0: Brighter future?
Eugene Zharkov
 

Similar to Javascript Styles and some tips (20)

PDF
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
PDF
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
PHP Conference Argentina
 
KEY
Backbone.js
Chris Neale
 
PDF
Workshop 5: JavaScript testing
Visual Engineering
 
PPT
Cappuccino @ JSConf 2009
tolmasky
 
PPTX
Java best practices
Ray Toal
 
PDF
Js hacks
Nishchit Dhanani
 
KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
PDF
Functional Javascript
guest4d57e6
 
PDF
Say It With Javascript
Giovanni Scerra ☃
 
PDF
Cocoa Design Patterns in Swift
Michele Titolo
 
PPT
25-functions.ppt
JyothiAmpally
 
PPTX
Taming that client side mess with Backbone.js
Jarod Ferguson
 
KEY
Apostrophe (improved Paris edition)
tompunk
 
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
PDF
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
PDF
Javascript: the important bits
Chris Saylor
 
PPTX
EcmaScript unchained
Eduard Tomàs
 
ZIP
Javascript Everywhere
Pascal Rettig
 
PDF
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
PHP Conference Argentina
 
Backbone.js
Chris Neale
 
Workshop 5: JavaScript testing
Visual Engineering
 
Cappuccino @ JSConf 2009
tolmasky
 
Java best practices
Ray Toal
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Functional Javascript
guest4d57e6
 
Say It With Javascript
Giovanni Scerra ☃
 
Cocoa Design Patterns in Swift
Michele Titolo
 
25-functions.ppt
JyothiAmpally
 
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Apostrophe (improved Paris edition)
tompunk
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Javascript: the important bits
Chris Saylor
 
EcmaScript unchained
Eduard Tomàs
 
Javascript Everywhere
Pascal Rettig
 
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
Ad

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Ad

Javascript Styles and some tips