Object Oriented JavaScript & jQuery
Intructor: Emre Kekeç
Estimated Time:
Company: Veripark
CONTENTS
OOJS JQUERY
• JS Functions • Basics
• Objects • DOM Operations
• Prototype • Intermediate topics
• Inheritance in JS • Writing Plugins
• Performance
• Events
• AJAX
© 2012 VeriPark 2
FUNCTIONS - Defining a Function
• Always returns a value ( undefined if not specified )
• Always returns a single value
– Use an array for more than one
© 2012 VeriPark 3
Calling a Function
• If missing or excessive arguments are used when
calling;
– undefined for missing & ignored if excessive
• The arguments is created for all functions.
– i.e. SomeFunction(‘foo’) // arguments[0] == foo TRUE
© 2012 VeriPark 4
Function Scopes
• Global Variable
– Defined outside any function
– Visible to everyone
• Local Variable ( Requires var !)
– Defined in a function
– Visible only within the function
© 2012 VeriPark 5
Variable Hiding & Hoisting
someVariable=10;
function F1() {
Undefined here
someVariable=5;
}
© 2012 VeriPark 6
Function Types
• Anonymous var operation = function(){
};
• Immediate (function (opToExecute){
opToExecute();
function inner(){
• Callback }
})(operation);
• Inner ( private )
© 2012 VeriPark 7
Closures
– OPTION 1 Global
• Return B from F2 Var A
• Return F2 from F1
F1
• Save the result in global &
Var B
execute
– OPTION 2 F2
• Replace F2 with global Var C
function
© 2012 VeriPark 8
OBJECTS – Declarative Syntax
var Car = {
color: <value> // primitive
accelerate : function(){ }, // method
owner : {
name: <value> // primitive
} //object ownership
}
© 2012 VeriPark 9
OBJECTS – Programmatic Syntax
function Account() {
this.number = <value> // primitive
this.displayBalance = function(){ }, // method
}
var checkingAccount = new Account();
© 2012 VeriPark 10
Accessing and Modifying Properties
• Dot or Array notation can be used
– Car.color, Car[accelerate](), Car.owner[name]
• Defining new properties are simple
– Car.Make = ‘BMW’;
• Deleting properties
– delete Car.color;
© 2012 VeriPark 11
Global Object
• Different for environments
– E.g. window for browser
• Owns the global properties
– globalVar == window.globalVar == this.globalVar
© 2012 VeriPark 12
Constructor
• Present as a property in all objects
– var anotherBmw = new bmw.constructor();
© 2012 VeriPark 13
Object References
• When an object is copied or passed to a function, it’s
reference is passed.
• When comparing, the references are compared
© 2012 VeriPark 14
A new insight to Functions
• The following all work:
• function sum(a,b){return a+b;}
• var sum = function(a,b){return a+b;};
• var sum = new function(‘a’,’b’,’return a+b;’);
– //Not recommended
© 2012 VeriPark 15
call & apply Methods
• Indirectly invokes a function
– someFunction.call();
• It’s power: The context(owner) can be changed!
– objectA.methodOfA(objectB);
– //this keyword refers to objectB!
• apply: Same as call but parameters are in array
– call(context,’a’,’b’) vs apply(context,[‘a’,’b’])
© 2012 VeriPark 16
PROTOTYPE - Definition
• We already know that functions are objects
– Methods: call, apply
– Properties: length, constructor
• prototype is a property on a function; if it is used as a
constructor; to define properties and methods.
• The prototype property is an object itself!
© 2012 VeriPark 17
Overriding Prototype Methods
• If you define an identically named member both in an
object and it’s prototype , object’s version is used
• hasOwnProperty returns true if the object owns the
property or false otherwise.
© 2012 VeriPark 18
Enumerating Properties
• for-in loop can be used to enumerate all properties of
an object including prototype properties:
– Enumeration can be turned on/off in ES5 +
(propertyIsEnumerable())
– Most built in JS methods are not enumerable
© 2012 VeriPark 19
Checking Prototype
• isPrototypeOf checks if a JS object is the prototype of
the object it is invoked on.
animal.isPrototypeOf(zebra);
© 2012 VeriPark 20
Getting the Prototype
• Object.getPrototypeOf() //ES5+
– var prototypename = Object.getPrototypeOf(zebra);
• _proto_ property is also a link on objects to their
prototypes on ES5+.
– Use when debugging but not in scripts!
• Both may not work in some & older browsers
© 2012 VeriPark 21
Tips & Tricks – Adding new members to standard JS
• Usually, changing the prototypes of built-in JS
functions is not recommended.
• Exception: A newer JS spec has a great function, and
you want to employ this in your project.
– Apply the new stuff to old JS core lib prototype.
– Always check the function’s existence!!
© 2012 VeriPark 22
Tips & Tricks – Messing with prototypes
• Unless you completely replace a prototype, it is live.
• If you replace a prototype, it’s constructor must be
reset!
© 2012 VeriPark 23
Tips & Tricks – Messing with prototypes
Dog
+bark();
Puppy1 can bark.
Dog.prototype +shakeTail(); Puppy1 can shake tail.
© 2012 VeriPark 24
Tips & Tricks – Messing with prototypes
Dog
+bark();
Puppy1 can bark. Puppy2 can shake tail.
Dog.prototype = {
Puppy2.constructor is a new object
shakeTail();
}; Puppy2.constructor = Dog;
//RESET WITH NEW PROTOTYPE
© 2012 VeriPark 25
REGULAR OOD (CLASS) vs JavaScript OOD (OBJECT)
PARENT
PARENT OBJECT
-properties
-methods
VS CHILD PROTOTYPE
CHILD
-childProperties
-childMethods
CHILD OBJECT
© 2012 VeriPark 26
Technique 1 – Prototype Chaining
OBJECT
__PROTO__
ANIMAL
__PROTO__
CAT
__PROTO__
© 2012 VeriPark 27
Using Intermediary Prototypes for Breaking Dependency
OBJECT
__PROTO__
ANIMAL
__PROTO__
ANIMALCLONE
__PROTO__
CAT
__PROTO__
© 2012 VeriPark 28
Technique 2 - Copy
• Shallow Copy
• Deep Copy (Also clone references)
© 2012 VeriPark 29
Multiple Inheritance : Mixin Objects / Functions
PARENT OBJECT 1 PARENT OBJECT 2
MIXIN OBJECT
CHILD PROTOTYPE
CHILD OBJECT
© 2012 VeriPark 30
Borrowing Constructors
Child Constructor Function
+property
+prototype
Parent Constructor Function
+property
+prototype
2.Extend Prototype
© 2012 VeriPark 31
JQUERY - Installation
• Use Google CDN
• Download your own version and place it in your project
(Preferred)
© 2012 VeriPark 32
Ready Event
$(document).ready(function(){
});
– window.onLoad() ?
© 2012 VeriPark 33
Selecting elements
• CSS Syntax
– $(‘p’), $(‘.userComments’), $(‘#username’)
• Javascript reference of the DOM element
© 2012 VeriPark 34
Selecting within a specific context
• $(‘a’, ‘body’), $(‘p’,’div.content’);
© 2012 VeriPark 35
Filtering the result set
$(‘li’).filter( function(index){
return index % 2 == 0;
});
© 2012 VeriPark 36
Finding descendant elements
• jQuery('p').find('em');
© 2012 VeriPark 37
DOM - Traversing
• eq(index)
• next()
• prev()
• parent()
• children()
• nextAll()
• prevAll()
© 2012 VeriPark 38
Operating on DOM elements
• append()
– appendTo() – Target version
• prepend()
– prependTo() – Target version
• after()
– insertAfter() – Target version
• before()
– insertBefore() – Target version
• wrap()
– wrapAll()
– wrapInner()
© 2012 VeriPark 39
Removing & Replacing DOM elements
• remove()
• replaceWith()
– replaceAll()
© 2012 VeriPark 40
Cloning DOM elements
• clone()
© 2012 VeriPark 41
Working on attributes
• attr()
• removeAttr(attributeName)
• Applies to the 1st element when run on a set!
© 2012 VeriPark 42
Dealing with element classes
• addClass()
• hasClass()
• removeClass()
• toggleClass()
© 2012 VeriPark 43
Attribute filtering
– [attr]
– [attr=val]
– [attr!=val]
– [attr^=val]
– [attr$=val]
– [attr~=val]
– [attr*=val]
© 2012 VeriPark 44
INTERMEDIATE TOPICS – Loops in jQuery
• $(selector).each(); //EXCLUSIVELY JQUERY OBJECTS
• JQuery.each(object,callback) // SUPPORTS ALL
© 2012 VeriPark 45
Converting jQuery Objects to DOM Objects
• RAW DOM OBJECT = $(selector).get();
• $jQueryCollection[0] – First element in the set
© 2012 VeriPark 46
Checking the index of an item
• $resultSet.index(elementToSearch)
• If the subject is not found, it returns -1
© 2012 VeriPark 47
Maintaining state
• $jQueryObject.data(object);
© 2012 VeriPark 48
Mapping an array
• $.map(source,callback)
© 2012 VeriPark 49
Handling library conflict and protecting the $ sign
• JQuery.noConflict();
• (function($){})(jQuery);
© 2012 VeriPark 50
PLUGINS – Composing Standards
• Name as jQuery.pluginName-version.js
• Protect the $
• Beware of what to return or if you need the call stack
• Always provide default options and get them
• Watch the this context
• Maintain state
© 2012 VeriPark 51
Context of this and return type
(function($){
$.fn.myPlugin = function() {
return this;
};
})(jQuery);
© 2012 VeriPark 52
Chainability
(function($){
$.fn.myPlugin = function() {
var array = [this[0]];
return this.pushStack(array);
};
})(jQuery);
© 2012 VeriPark 53
PERFORMANCE - Writing faster selectors
• Use the most recent jQuery plugin if possible
• Reduce the selection context size
• Pay attention to Sizzle engine execution order
• Order of selection performance from high to low:
– jQuery built-in filters
– DOM id,
– class,
– tagname
© 2012 VeriPark 54
DOM operations
• When adding new content to DOM, group items in a
container
• Prefer direct JavaScript functions over jQuery when
performance is critical
© 2012 VeriPark 55
Better loops
• jQuery each has a performance hit since it involves
callbacks.
– Prefer for loops when performance is critical
– Avoid for-in on jQuery objects! (WHY?)
• Pay attention to memory leaks in the loop
– Cache selected items in a variable before the loop
© 2012 VeriPark 56
Reduce name lookups
• The closure concept in OOJS section is handy but
requires a global lookup
• Avoid global lookups by creating cached instances of
global or higher scoped functions/variables
© 2012 VeriPark 57
EVENTS - Definition
EVENTS CAN OCCUR WHEN
– An object is clicked or the user enters input
– When the document finishes loading to the browser from the
server
– When an AJAX call gets the response asynchronously
– A totally custom event is fired in response to something
© 2012 VeriPark 58
Event Handler Binding Methods
• bind() – Attaches to element, obsolete
• live() – Attaches to document, obsolete
• delegate() – Attaches to every level, older but
supported by many versions
• on() – Best approach, but supported in newer versions
© 2012 VeriPark 59
Shortcut handlers
– There are many shortwired event handlers built-in to
jQuery with their event names:
click()
ready()
keyDown()
load() … and much more
© 2012 VeriPark 60
Passing data to handlers
Static Data
– The event handler can receive a data object
• .on( events [, selector ] [, data ], handler(eventObject) )
Dynamic Data
– METHOD 1 - data() method of jQuery can hold DOM state.
– METHOD 2 - trigger() method can be supplied with arguments
• Passing: Trigger(‘click’,’data’)
• Usage: .click(function(event,data))
© 2012 VeriPark 61
Event namespaces
• A special notation is present to classify events
in groups similar to CSS class.
– Eventname.Namespace
© 2012 VeriPark 62
Preventing Propagation & Execution
• preventDefault()
• stopPropagation()
• stopImmediatePropagation()
© 2012 VeriPark 63
Event Targets
– event.target
– event.currentTarget
– When delegation is used they are both the same
© 2012 VeriPark 64
AJAX – Methods to use
– load(url,data,completeCallback)
• Loads an HTML fragment into an element
– $.get(url,data,callback,datatype)
• Issues GET request with callback
– $.post(url,data,callback,datatype)
• Issues POST request with callback
– $.getJSON(url,data,callback)
• Gets JSON data with callback
– $.getScript()
• Gets JS code with callback IF the request suceeds (Not JS Execution!)
© 2012 VeriPark 65
The general purpose .ajax() method
– $.ajax(url,settings)
– SETTINGS
• Context
• Filters
• Status Handlers
• XMLHttpObject …
• Deferred and Promise objects ( When – Then )
© 2012 VeriPark 66
JSONP in Action
SCRIPT
JSON { data }
© 2012 VeriPark 67
JSONP in Action
SOLUTION?
SCRIPT
JSON { data }
SCRIPT CONTENT OK CDN e.g. jQ uery
© 2012 VeriPark 68
JSONP in Action
SCRIPT
JSON { data }
When loaded
Runs Callback
$.getScript (AJAX) Create a script that calls
a function with server JSON data
© 2012 VeriPark 69
THANK YOU !