SlideShare une entreprise Scribd logo
1  sur  63
Télécharger pour lire hors ligne
Intro to jQuery
Web Development 101
Lesson 03.01
jQuery is great
Advanced Javascript.
Web Development 101
Lesson 03.01
OR
What 80% of Javascript programmers don’t know
about their own language.
// The .bind method from Prototype.js	
Function.prototype.bind = function() {	
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();	
return function() {	
return fn.apply(
object,
args.concat(
Array.prototype.slice.call(arguments)
)
);	
};	
};
What ways can we define functions?
function funcA(){ return true; }	
var funcB = function(){ return true; };	
window.funcC = function(){ return true; };
!

assert( funcA() && funcB() && funcC() );
var funcB = function(){ return true; };	
window.funcC = function(){ return true; };
!

assert( funcA() && funcB() && funcC() );
!

function funcA(){ return true; }
function stealthCheck(){	
assert( stealth() );	
!

return stealth();	
!

function stealth(){ return true; }	
}	
!

stealthCheck();
function factorial(n) {	
return n * (n > 1 ? factorial(n - 1) : 1);	
}	
!

factorial(10);
var factorial = function f(n) {	
return n * (n > 1 ? f(n - 1) : 1);	
}	
!

factorial(10); // Works
f(10);
// Undefined function
Is a function an object?
var obj = {};	
var fn = function(){};
!

obj.prop = "some value";	
fn.prop = "some value";
var factorial = function f(n) {	
f.cache = f.cache || {};	
if (!f.cache[n]) {	
f.cache[n] = n * (n > 1 ? f(n - 1) : 1);	
}	
return f.cache[n];	
}	
!

factorial(10);	
factorial(9);	
factorial(20);
How does `this` work?
var katana = {	
isSharp: true,	
use: function(){	
this.isSharp = false;	
}	
};	
!

katana.use();	
katana.isSharp === false;
function katana(){	
this.isSharp = true;	
}	
katana();	
isSharp === true;	
!
!

var shuriken = {	
toss: function(){	
this.isSharp = true;	
}	
};	
shuriken.toss();	
shuriken.isSharp === true;
How do I change `this`?
var object = {};	
function fn(){	
return this;	
}
!

fn() === this === window;
!

fn.call(object) === object;
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr(a){	
return this[a];	
}
!

getAttr.call(object, ‘a’) === ‘Jeremiah’;
!

getAttr.apply(object, [‘b’]) === ‘Baruch’;
Can I instantiate a function?
function Pioneer(){	
this.name = "Pioneer";	
}	
!

joe = Pioneer();	
joe === undefined;
!

joe = new Pioneer();
joe.name == "Pioneer";
function Pioneer(){	
this.hasBibleStudy = false;
!
this.preach = function() {
this.hasBibleStudy = true;	
};	
}	
!
jack = new Pioneer();
jill = new Pioneer();
!
jack.hasBibleStudy === false;
jill.hasBibleStudy === false;
!
jack.preach();
!
jack.hasBibleStudy === true;
jill.hasBibleStudy === false;
function Pioneer(){	
this.hasBibleStudy = false;
!
this.preach = function() {
this.hasBibleStudy = true;	
};	
}	
!
jack = Pioneer();
jill = Pioneer();
!
jack.hasBibleStudy === false; // Fatal Type Error
jill.hasBibleStudy === false;
!
jack.preach();
!
jack.hasBibleStudy === true;
jill.hasBibleStudy === false;
Can I build a function with variable
number of arguments?
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr(a){	
return this[a];	
}
!

getAttr.apply(object, [‘b’]) === ‘Baruch’;
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr() {
var out = [], i;
for (i = 0; i < arguments.length; i++) {
out.push( this[ arguments[i] ] );
}
return out;	
}
!

getAttr.apply(object, [‘a’, ‘b’]) ===
[‘Jeremiah’, ‘Baruch’];
function smallest(array){	
return Math.min.apply( Math, array );	
}
!

function largest(array){	
return Math.max.apply( Math, array );	
}
!

assert(smallest([0, 1, 2, 3]) == 0);	
assert(largest([0, 1, 2, 3]) == 3);
function smallest() {	
return Math.min.apply( Math, arguments );	
}
!

function largest() {	
return Math.max.apply( Math, arguments );	
}
!

assert(smallest(0, 1, 2, 3) == 0);	
assert(largest(0, 1, 2, 3) == 3);
function highest(){	
return arguments.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3;
function highest(){	
return arguments.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3; // Fatal Error.
`arguments` isn’t actually an array
function highest() {
var argArray = Array().slice.call(arguments);	
return argArray.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3;
How do Closures work?
var a = 5;

!
function runMe(a) {	
assert( a == ___, "Check the value of a." );	

!
function innerRun(){	
assert( b == ___, "Check the value of b." );	
assert( c == ___, "Check the value of c." );	
}	

!
var b = 7;	
innerRun();	
var c = 8;	
}

!
runMe(6);	

!
for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == ___, "Check the value of d." );	
}, 100);	
}
var a = 5;

!
function runMe(a) {	
assert( a == 6, "Check the value of a." );	

!
function innerRun(){	
assert( b == 7, "Check the value of b." );	
assert( c == undefined, "Check the value of c." );	
}	

!
var b = 7;	
innerRun();	
var c = 8;	
}

!
runMe(6);	

!
for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == 3, "Check the value of d." );	
}, 100);	
}
!

for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == 3, "Check the value of d." );	
}, 100);	
}
for (var d = 0; d < 3; d++) {	
(function (d) {	
setTimeout(function () {	
console.log(d);	
}, 100);	
}(d));	
}
Code smell: Don’t make closures
inside a loop. Normally.
How do I make a class?
#!/usr/bin/env python
!

class Pioneer(object):
def __init__(self, name):
self.name = name
self.bibleStudies = 0
!

def preach(self):
self.bibleStudies += 1
!

joe = Pioneer(“Joe”)
joe.preach();
#!/usr/bin/env php
!
class Pioneer {
private name;
private bibleStudies;
!
public function __construct(name) {
this.name = name;
this.bibleStudies = 0;
}
!
public function preach() {
this.bibleStudies++;
}
}
!
joe = new Pioneer(“Joe”);
joe->preach();
Write `Pioneer` in JS.
var Pioneer = function(name) {
this.name = name;
this.bibleStudies = 0;
!

this.preach = function() {
this.bibleStudies++;
};
};
!

joe = new Pioneer(“Joe”);
joe.preach();
var Pioneer = function(name) {
this.name = name;
this.bibleStudies = 0;
};
!

Pioneer.prototype = {};
Pioneer.prototype.preach = function() {
this.bibleStudies++;
};
!

joe = new Pioneer(“Joe”);
joe.preach();
Inheritance. Prototypal Inheritance.
var Pioneer = function (name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

Pioneer.prototype = {};	
Pioneer.prototype.preach = function () {	
this.bibleStudies++;	
};	

!

var SpecialPioneer = function(name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

SpecialPioneer.prototype = new Pioneer();	
SpecialPioneer.prototype.preach = function () {	
this.bibleStudies += 5;	
};	

!

var joe = new Pioneer("Joe"),	
jeremy = new SpecialPioneer('Jeremy');	

!

joe.preach();	
jeremy.preach();
Enforcing Function Context
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	
!

var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click;	
document.getElementById("results").appendChild(elem);	
!

elem.onclick();
!

Button.clicked === undefined;	
elem.clicked === true;
function bind(context, name){	
return function() {	
return context[name].apply(context, arguments);	
};	
}	

!
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = bind(Button, "click");	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();

!
Button.clicked === true;
elem.clicked === undefined;
Function.prototype.bind = function(object) {	
var fn = this;	
return function(){	
return fn.apply(object, arguments);	
};	
};	

!
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click.bind(Button);	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();

!
Button.clicked === true;
Back to our original goal
// The .bind method from Prototype.js	
Function.prototype.bind = function() {	
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();	
return function() {	
return fn.apply(
object,
args.concat(
Array.prototype.slice.call(arguments)
)
);	
};	
};
Function.prototype.bind = function(){	
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();	
return function(){	
return fn.apply(object,	
args.concat(Array.prototype.slice.call(arguments)));	
};	
};	

!
var Button = {	
click: function(value) {	
this.clicked = value;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click.bind(Button, “I was clicked!”);	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();	

!
Button.clicked === “I was clicked!”
Functions can be defined 3
ways


Closures can be used to cache
values for later, including
execution scope.


Functions are just objects that
you can execute.


Objects inherit from each other
using prototypes.


The `this` keyword is bound to
function context


Build in object prototypes can
be extended.


No classes, just objects.


All of that works without
including jQuery at all.
Moral of the story
Javascript is a great, although quirky, language.

Prototypal inheritance works similarly, but not exactly like class
inheritance.

jQuery is a great library. You should use it for DOM and AJAX code.

Reading API documentation will teach you jQuery. A good
understanding of Javascript is harder to come by.
:rewind
var Pioneer = function (name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

Pioneer.prototype = {};	
Pioneer.prototype.preach = function () {	
this.bibleStudies++;	
};	

!

var SpecialPioneer = function(name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

SpecialPioneer.prototype = new Pioneer();	
SpecialPioneer.prototype.preach = function () {	
this.bibleStudies += 5;	
};	

!

var joe = new Pioneer("Joe"),	
jeremy = new SpecialPioneer('Jeremy');	

!

joe.preach();	
jeremy.preach();
Let’s make inheritance better.
var Person = Class.extend({	
init: function (isDancing) {	
this.dancing = isDancing;	
},	
dance: function () {	
return this.dancing;	
}	
});	

!

var Ninja = Person.extend({	
init: function () {	
this._super(false);	
},	
dance: function () {	
// Call the inherited version of dance()	
return this._super();	
},	
swingSword: function () {	
return true;	
}	
});	

!

var p = new Person(true);	
p.dance(); // => true	

!

var n = new Ninja();	
n.dance(); // => false	
n.swingSword(); // => true	

!

// Should all be true	
p instanceof Person && p instanceof Class && n instanceof Ninja && n instanceof Person && n instanceof Class

Contenu connexe

Tendances

Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupBrian Gesiak
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleMarcio Klepacz
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
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 JavaScriptGuy Royse
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreNicolas Carlo
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of CodeJoe Morgan
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of TestingMarco Cedaro
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersFITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...Haris Mahmood
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2tonvanbart
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 

Tendances (18)

Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental Setup
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and Nimble
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
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
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscore
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of Code
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of Testing
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 

Similaire à 04 Advanced Javascript

srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxwhitneyleman54422
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)Ryan Ewing
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented JavascriptDaniel Ku
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
Modern JavaScript Engine Performance
Modern JavaScript Engine PerformanceModern JavaScript Engine Performance
Modern JavaScript Engine PerformanceCatalin Dumitru
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 

Similaire à 04 Advanced Javascript (20)

srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Modern JavaScript Engine Performance
Modern JavaScript Engine PerformanceModern JavaScript Engine Performance
Modern JavaScript Engine Performance
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 

Plus de crgwbr

Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserifycrgwbr
 
07 Integration Project Part 1
07 Integration Project Part 107 Integration Project Part 1
07 Integration Project Part 1crgwbr
 
06 Map Reduce
06 Map Reduce06 Map Reduce
06 Map Reducecrgwbr
 
05 Web Services
05 Web Services05 Web Services
05 Web Servicescrgwbr
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuerycrgwbr
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascriptcrgwbr
 
01 Introduction To CSS
01 Introduction To CSS01 Introduction To CSS
01 Introduction To CSScrgwbr
 
08 Integration Project Part 2
08 Integration Project Part 208 Integration Project Part 2
08 Integration Project Part 2crgwbr
 

Plus de crgwbr (8)

Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserify
 
07 Integration Project Part 1
07 Integration Project Part 107 Integration Project Part 1
07 Integration Project Part 1
 
06 Map Reduce
06 Map Reduce06 Map Reduce
06 Map Reduce
 
05 Web Services
05 Web Services05 Web Services
05 Web Services
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuery
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
 
01 Introduction To CSS
01 Introduction To CSS01 Introduction To CSS
01 Introduction To CSS
 
08 Integration Project Part 2
08 Integration Project Part 208 Integration Project Part 2
08 Integration Project Part 2
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
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...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
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 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
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 WorkerThousandEyes
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

04 Advanced Javascript

  • 1. Intro to jQuery Web Development 101 Lesson 03.01
  • 3.
  • 5. OR What 80% of Javascript programmers don’t know about their own language.
  • 6. // The .bind method from Prototype.js Function.prototype.bind = function() { var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { return fn.apply( object, args.concat( Array.prototype.slice.call(arguments) ) ); }; };
  • 7. What ways can we define functions?
  • 8. function funcA(){ return true; } var funcB = function(){ return true; }; window.funcC = function(){ return true; }; ! assert( funcA() && funcB() && funcC() );
  • 9. var funcB = function(){ return true; }; window.funcC = function(){ return true; }; ! assert( funcA() && funcB() && funcC() ); ! function funcA(){ return true; }
  • 10. function stealthCheck(){ assert( stealth() ); ! return stealth(); ! function stealth(){ return true; } } ! stealthCheck();
  • 11. function factorial(n) { return n * (n > 1 ? factorial(n - 1) : 1); } ! factorial(10);
  • 12. var factorial = function f(n) { return n * (n > 1 ? f(n - 1) : 1); } ! factorial(10); // Works f(10); // Undefined function
  • 13. Is a function an object?
  • 14. var obj = {}; var fn = function(){}; ! obj.prop = "some value"; fn.prop = "some value";
  • 15. var factorial = function f(n) { f.cache = f.cache || {}; if (!f.cache[n]) { f.cache[n] = n * (n > 1 ? f(n - 1) : 1); } return f.cache[n]; } ! factorial(10); factorial(9); factorial(20);
  • 17. var katana = { isSharp: true, use: function(){ this.isSharp = false; } }; ! katana.use(); katana.isSharp === false;
  • 18. function katana(){ this.isSharp = true; } katana(); isSharp === true; ! ! var shuriken = { toss: function(){ this.isSharp = true; } }; shuriken.toss(); shuriken.isSharp === true;
  • 19. How do I change `this`?
  • 20. var object = {}; function fn(){ return this; } ! fn() === this === window; ! fn.call(object) === object;
  • 21. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr(a){ return this[a]; } ! getAttr.call(object, ‘a’) === ‘Jeremiah’; ! getAttr.apply(object, [‘b’]) === ‘Baruch’;
  • 22. Can I instantiate a function?
  • 23. function Pioneer(){ this.name = "Pioneer"; } ! joe = Pioneer(); joe === undefined; ! joe = new Pioneer(); joe.name == "Pioneer";
  • 24. function Pioneer(){ this.hasBibleStudy = false; ! this.preach = function() { this.hasBibleStudy = true; }; } ! jack = new Pioneer(); jill = new Pioneer(); ! jack.hasBibleStudy === false; jill.hasBibleStudy === false; ! jack.preach(); ! jack.hasBibleStudy === true; jill.hasBibleStudy === false;
  • 25. function Pioneer(){ this.hasBibleStudy = false; ! this.preach = function() { this.hasBibleStudy = true; }; } ! jack = Pioneer(); jill = Pioneer(); ! jack.hasBibleStudy === false; // Fatal Type Error jill.hasBibleStudy === false; ! jack.preach(); ! jack.hasBibleStudy === true; jill.hasBibleStudy === false;
  • 26. Can I build a function with variable number of arguments?
  • 27. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr(a){ return this[a]; } ! getAttr.apply(object, [‘b’]) === ‘Baruch’;
  • 28. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr() { var out = [], i; for (i = 0; i < arguments.length; i++) { out.push( this[ arguments[i] ] ); } return out; } ! getAttr.apply(object, [‘a’, ‘b’]) === [‘Jeremiah’, ‘Baruch’];
  • 29. function smallest(array){ return Math.min.apply( Math, array ); } ! function largest(array){ return Math.max.apply( Math, array ); } ! assert(smallest([0, 1, 2, 3]) == 0); assert(largest([0, 1, 2, 3]) == 3);
  • 30. function smallest() { return Math.min.apply( Math, arguments ); } ! function largest() { return Math.max.apply( Math, arguments ); } ! assert(smallest(0, 1, 2, 3) == 0); assert(largest(0, 1, 2, 3) == 3);
  • 31. function highest(){ return arguments.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3;
  • 32. function highest(){ return arguments.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3; // Fatal Error.
  • 34. function highest() { var argArray = Array().slice.call(arguments); return argArray.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3;
  • 36. var a = 5; ! function runMe(a) { assert( a == ___, "Check the value of a." ); ! function innerRun(){ assert( b == ___, "Check the value of b." ); assert( c == ___, "Check the value of c." ); } ! var b = 7; innerRun(); var c = 8; } ! runMe(6); ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == ___, "Check the value of d." ); }, 100); }
  • 37. var a = 5; ! function runMe(a) { assert( a == 6, "Check the value of a." ); ! function innerRun(){ assert( b == 7, "Check the value of b." ); assert( c == undefined, "Check the value of c." ); } ! var b = 7; innerRun(); var c = 8; } ! runMe(6); ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == 3, "Check the value of d." ); }, 100); }
  • 38. ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == 3, "Check the value of d." ); }, 100); }
  • 39. for (var d = 0; d < 3; d++) { (function (d) { setTimeout(function () { console.log(d); }, 100); }(d)); }
  • 40. Code smell: Don’t make closures inside a loop. Normally.
  • 41. How do I make a class?
  • 42. #!/usr/bin/env python ! class Pioneer(object): def __init__(self, name): self.name = name self.bibleStudies = 0 ! def preach(self): self.bibleStudies += 1 ! joe = Pioneer(“Joe”) joe.preach();
  • 43. #!/usr/bin/env php ! class Pioneer { private name; private bibleStudies; ! public function __construct(name) { this.name = name; this.bibleStudies = 0; } ! public function preach() { this.bibleStudies++; } } ! joe = new Pioneer(“Joe”); joe->preach();
  • 45. var Pioneer = function(name) { this.name = name; this.bibleStudies = 0; ! this.preach = function() { this.bibleStudies++; }; }; ! joe = new Pioneer(“Joe”); joe.preach();
  • 46. var Pioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function() { this.bibleStudies++; }; ! joe = new Pioneer(“Joe”); joe.preach();
  • 48. var Pioneer = function (name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function () { this.bibleStudies++; }; ! var SpecialPioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! SpecialPioneer.prototype = new Pioneer(); SpecialPioneer.prototype.preach = function () { this.bibleStudies += 5; }; ! var joe = new Pioneer("Joe"), jeremy = new SpecialPioneer('Jeremy'); ! joe.preach(); jeremy.preach();
  • 50. var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click; document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === undefined; elem.clicked === true;
  • 51. function bind(context, name){ return function() { return context[name].apply(context, arguments); }; } ! var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = bind(Button, "click"); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === true; elem.clicked === undefined;
  • 52. Function.prototype.bind = function(object) { var fn = this; return function(){ return fn.apply(object, arguments); }; }; ! var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click.bind(Button); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === true;
  • 53. Back to our original goal
  • 54. // The .bind method from Prototype.js Function.prototype.bind = function() { var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { return fn.apply( object, args.concat( Array.prototype.slice.call(arguments) ) ); }; };
  • 55. Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; ! var Button = { click: function(value) { this.clicked = value; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click.bind(Button, “I was clicked!”); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === “I was clicked!”
  • 56.
  • 57. Functions can be defined 3 ways Closures can be used to cache values for later, including execution scope. Functions are just objects that you can execute. Objects inherit from each other using prototypes. The `this` keyword is bound to function context Build in object prototypes can be extended. No classes, just objects. All of that works without including jQuery at all.
  • 58. Moral of the story
  • 59. Javascript is a great, although quirky, language. Prototypal inheritance works similarly, but not exactly like class inheritance. jQuery is a great library. You should use it for DOM and AJAX code. Reading API documentation will teach you jQuery. A good understanding of Javascript is harder to come by.
  • 61. var Pioneer = function (name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function () { this.bibleStudies++; }; ! var SpecialPioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! SpecialPioneer.prototype = new Pioneer(); SpecialPioneer.prototype.preach = function () { this.bibleStudies += 5; }; ! var joe = new Pioneer("Joe"), jeremy = new SpecialPioneer('Jeremy'); ! joe.preach(); jeremy.preach();
  • 63. var Person = Class.extend({ init: function (isDancing) { this.dancing = isDancing; }, dance: function () { return this.dancing; } }); ! var Ninja = Person.extend({ init: function () { this._super(false); }, dance: function () { // Call the inherited version of dance() return this._super(); }, swingSword: function () { return true; } }); ! var p = new Person(true); p.dance(); // => true ! var n = new Ninja(); n.dance(); // => false n.swingSword(); // => true ! // Should all be true p instanceof Person && p instanceof Class && n instanceof Ninja && n instanceof Person && n instanceof Class