SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
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');

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Improving the java type system
Improving the java type systemImproving the java type system
Improving the java type system
João Loff
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 
bullismo e scuola primaria
bullismo e scuola primariabullismo e scuola primaria
bullismo e scuola primaria
imartini
 
Angular 2.0: Brighter future?
Angular 2.0: Brighter future?Angular 2.0: Brighter future?
Angular 2.0: Brighter future?
Eugene Zharkov
 

Was ist angesagt? (20)

Oop in java script
Oop in java scriptOop in java script
Oop in java script
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By LuckStop Programming in JavaScript By Luck
Stop Programming in JavaScript By Luck
 
Functions
FunctionsFunctions
Functions
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Lecture05
Lecture05Lecture05
Lecture05
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Improving the java type system
Improving the java type systemImproving the java type system
Improving the java type system
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
bullismo e scuola primaria
bullismo e scuola primariabullismo e scuola primaria
bullismo e scuola primaria
 
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
 
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 
Angular 2.0: Brighter future?
Angular 2.0: Brighter future?Angular 2.0: Brighter future?
Angular 2.0: Brighter future?
 

Ähnlich wie Javascript Styles and some tips

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 

Ähnlich wie Javascript Styles and some tips (20)

A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
 
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
2013 - Nate Abele: HTTP ALL THE THINGS: Simplificando aplicaciones respetando...
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Js hacks
Js hacksJs hacks
Js hacks
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Javascript Styles and some tips