advance js and oop
TRANSCRIPT
Boutique product development companyIt is amazing what you can accomplish when you have a client-centric team to deliver outstanding products.
Abuzer / Software Engineer
Topics Covered
• Some Myths
• Browser Console and Firebug
• Console Log
• Binary Assignment
• Data Types
• Anonymous Functions
Abuzer / Software Engineer
Topics Covered
• Array
• Objects• Dot-Style and Array-Style property access
• Functions• Functions are Objects
• Return Value
• Module Pattern• Over View
• Pros and Cons
• Scope• Inner Functions
• Closure
• Context• Changing Context
• Call() function
• Apply() function
• Classes
• OOP
• Constructor functions• Using the Constructor
• constructor property
• Methods• Public Methods
• Privileged Methods
• Private Methods
• Inheritance
• Prototype• Prototype usage
• Own properties vs. prototype’s
• Prototypal inheritance
• Inheritance by copying
• Wrapping Up
Abuzer / Software Engineer
Some Myths
• JavaScript is not Object Oriented
• JavaScript does not support data hiding, i.e. everything is public
• JavaScript is related to Java
• JavaScript was developed by Sun Microsystems
Abuzer / Software Engineer
Browser Console and Firebug
• You can test JavaScript code in consoles.
• F12 shortcut key to open console
Abuzer / Software Engineer
Console Logging
• Console.log( “ message” );
• Console.warn( “ message” );
• Console.error( “ message” );
• Console.table( Array , Object);
Abuzer / Software Engineer
Binary Assignment
Set a default value only if the variable doesn’t have a value yet.
// Traditional ternary assignment
var myVar = myVar ? myVar : 0;
// Binary assignment
var myVar = myVar || 0;
Abuzer / Software Engineer
Data Types
• Primitive:
– number – 1, 3, 1001, 11.12, 2e+3
– string – "a", "confiz", "0"
– boolean – true | false
– null
– undefined
• Objects
– everything else…
Abuzer / Software Engineer
Anonymous Functions
In JavaScript functions are treated as values
• Functions can be assigned to a variable
• Functions can be passed as parameter to other function
Abuzer / Software Engineer
Anonymous Functions ...
// Using an anonymous function as an argument
setTimeout( function () {
alert( “Refresh” );
}, 1000
);// Using a function as a variable
var myFunc = function () {
alert( “Refresh” );
};
setTimeout(myFunc, 1000);
Abuzer / Software Engineer
Array
• Arrays are objects too
• Some useful methods>>> var a = [1,3,2];
>>> a[0]
1
>>> typeof a
"object"
Abuzer / Software Engineer
Objects
Almost everything written in JavaScript is an object. e.g. array, functions
Objects can be though of as a collection of properties—much like a hash in other languages
Abuzer / Software Engineer
Object ...
var obj = {
shiny: true,
isShiny: function() {
return this.shiny;
}
};
obj.isShiny(); // true
Abuzer / Software Engineer
Dot-Style and Array-Style property access
var sampleObj = {
color: “blue”,
width: “16px”
};
// Traditional dot-style access
alert( sampleObj.color == “blue” );
// Alternative array-style access
alert( sampleObj[“width”] == “16px” );
Abuzer / Software Engineer
Functions
• functions are objects
• they have properties
• they have methods
• can be copied, deleted, augmented...
• special feature: invokable
Abuzer / Software Engineer
Functions
function say(what) {
return what;
}
var say = function(what) {
return what;
};
Abuzer / Software Engineer
Return Value
• All functions always return a value
• If a function doesn’t return a value explicitly, it returns undefined
• Functions can return objects, including other functions
Abuzer / Software Engineer
Module Pattern
Modules are isolated pieces of code that when well designed, work independently of the other module, there fore can be added or removed as necessary
Abuzer / Software Engineer
Overview
var Calculator = function(eq)(//private member var result= document.getElementByld(eq);return {//expose public member
add: function(x, y) {var val = x + y;result.innerHTML = val;
}}var calculator = new Calculator(eq);Calculator.add(2, 2);
Abuzer / Software Engineer
Pros and Cons
• Pros:
– "Modularize" code into re-useable objects
– Variables/functions taken out of global namespace
– Expose only public members while hiding private members
• Cons:
– Functions may be duplicated across objects in memory when not using singleton
– Not easy to extend
Abuzer / Software Engineer
Scope
• Only functions have scope. Blocks (if, while, for, switch) do not.
• All variables are within the global scope unless they are defined within a function.
• All global variables actually become properties of the window object
• When variables are not declared using the var keyword, they declared globally.
Abuzer / Software Engineer
Scope...
var foo = “original”; // foo is now a global variable
if ( true ) {foo = “new”; // Global foo now equals “new”
}
// create function to modify its own foo variablefunction test () {
var foo = “old”;}
test();
alert( foo == “new” ); // Global foo still equals “new”
Abuzer / Software Engineer
Scope: Inner Functions
Functions can be defined within one anotherInner functions have access to the outer function’s variables and parameters.function getRandomInt(max) {
var randNum = Math.random() * max;
function ceil() {
return Math.ceil(randNum);
}
return ceil(); // Notice that no arguments are passed
}// Alert random number between 1 and 5
alert( getRandomInt(5) );
Abuzer / Software Engineer
Closure
• An inner function that always access to the functions and parameters of the outer function, even after the outer function has returned .
• This allows you to effectively pass variables to functions that may not be called for some time.
Abuzer / Software Engineer
Closure ...
function delayedAlert (message, delay) {
// Set an enclosed callback
setTimeout( function () {
// Use message variable passed to outer function
alert(message);
}, delay);
}
// Display a message with a 5 second delay
delayedAlert(“Refresh”, 5000);
Abuzer / Software Engineer
Context
Your code will always be running within the context of another objectContext is maintained through the use of the “this” variable.
function increment() {
this.x = this.x || 0;
return this.x++;
};
alert( increment() == 0 ); ??
alert( increment() == 1 ); ??
Abuzer / Software Engineer
Context ...
var myObject = {
set: function (newVal) { this.val = newVal; }
};
alert( myObject.val == null ); // val property not set yet
myObject.set(“Refresh”);
alert( myObject.val == “Refresh” ); // val equals “Refresh”
// Change the context of set() to the window object
window.set = myObject.set;
window.set( “Refresh Page” );
alert( myObject.val == “Refresh” );
alert( window.val == “Refresh Page” );
Abuzer / Software Engineer
Changing Context
JavaScript provides two handy functions for executing a function within the context of another function:
call( )
apply( )
Abuzer / Software Engineer
Call() function
Using call() — Arguments passed by name
// Simple function to change the color style of a node
function changeColor (newColor) {this.style.color = newColor;
}
// window.changeColor has no style property, so call fails
changeColor( “red” );
// Grab the DOM node with the id “required”
var reqField = document.getElementById( “required” );
// Call changeColor() within reqField’s context
changeColor.call( reqField, “red” );
Abuzer / Software Engineer
Apply() function
Using apply() — Arguments passed as an array
// Simple function to change the color style of a nodefunction changeColor (newColor) {
this.style.color = newColor;}
// Set the text color of the body element
function setBodyTextColor () {changeColor.apply( document.body, arguments );
}
setBodyTextColor( “black” );
Abuzer / Software Engineer
Classes
• No such thing in JavaScript
• JavaScript doesn’t have a concept of classes like other object-oriented languages
• Classes are simulated using a concept called prototypal inheritance
Abuzer / Software Engineer
OOP
• Now let’s apply all of this information to a more classical view of OOP in JavaScript:
– Constructors
– Object Methods
– Public
– Private
– Privileged
Abuzer / Software Engineer
Constructor functions
• when invoked with new, functions return an object known as this
• you can modify this before it’s returned
Abuzer / Software Engineer
var Person = function(name) {
this.name = name;
this.getName = function() {
return this.name;
};
};
Abuzer / Software Engineer
Using the Constructor
var me = new Person("Stoyan");
me.getName(); // "Stoyan"
Abuzer / Software Engineer
constructor property
>>> function Person(){};
>>> var jo = new Person();
>>> jo.constructor === Person
true
Abuzer / Software Engineer
Public Methods
One way to create a public method—a function that can be freely reference by code outside your object—is to attach it to the object’s prototype.
An object’s prototype is a special property that acts as a base reference of your object.
This prototype object is copied and applied to all new instances of your object.
Abuzer / Software Engineer
// Our User object written a different way
var User = function (name) {
this.name = name;
}
// Add a public accessor method for name
User.prototype.getName = function () {
return this.name;
}
var me = new User( “Abuzer” );
alert( me.getName() == “Abuzer” );
Abuzer / Software Engineer
“Privileged” Methods
• The term privileged method was coined by Douglas Crockford. It is not a formal construct, but rather a technique.
• Privileged methods essentially have one foot in the door:
• Then can access private methods and values within the object
• They are also publicly accessible
Abuzer / Software Engineer
// Our User object with some tweaks
var User = function (name, age) {
var year = (new Date()).getFullYear() – age;
this.getYearBorn = function () {
return year;
};
};
// Create a new User
var me = new User( “Abuzer”, 24 );
// Access privileged method to access private year value
alert( me.getYearBorn() == 1990 );
// Fails because year is private
alert( me.year == null );
Abuzer / Software Engineer
Private Methods
// Our User object with some changesvar User = function (name) {
this.name = name;
function welcome () {alert( “Welcome back, ” + this.name);
}
welcome();}
// Create a new User var me = new User( “Abuzer” ); // Alerts: “Welcome, Abuzer.”
// Fails because welcome is not a public methodme.welcome();
Abuzer / Software Engineer
Prototype
• … is a property of the function objects
• Only function Objects can have prototype property
>>> var boo = function(){};
>>> typeof boo.prototype
"object"
>> console.log( foo.prototype ); // Object {}
• The objects have a secret link to the prototype of the constructor that created them
• __proto__ is not directly exposed in all browsers
Abuzer / Software Engineer
var Person = function(name) {
this.name = name;
};
Person.prototype.say =
function(){
return this.name;
};
Abuzer / Software Engineer
>>> var dude = new
Person('dude');
>>> dude.name;
"dude"
>>> dude.say();
"dude"
Abuzer / Software Engineer
say() is a property of the
prototype object
but it behaves as if it's a
property of the dude object
Abuzer / Software Engineer
Own properties vs. prototype’s
>>> dude.hasOwnProperty('name');
true
>>> dude.hasOwnProperty('say');
false
Abuzer / Software Engineer
Prototypal inheritance
• Class free
• Objects inherits from Objects
• An object contains a secret link to another object
• Mozilla calls it __protovar newObject = object(oldObject);
Abuzer / Software Engineer
_proto_
Parent Constructor
function NormalObject() {
this.name = 'normal';
this.getName = function() {
return this.name;
};
}
Abuzer / Software Engineer
Child Constructor
function PreciousObject(){
this.shiny = true;
this.round = true;
}
Abuzer / Software Engineer
A child object
var crystal_ball = new
PreciousObject();
crystal_ball.name = 'Crystal Ball.';
crystal_ball.round; // true
crystal_ball.getName(); // "Crystal
Ball."
Abuzer / Software Engineer
Two Objects
var shiny = {
shiny: true,
round: true
};
var normal = {
name: 'name me',
getName: function() {
return this.name;
}
};
Abuzer / Software Engineer
Extend()
function extend(parent, child) {
for (var i in parent) {
child[i] = parent[i];
}
}
Abuzer / Software Engineer
>>> var parent = {a: 1};
>>> var child = object(parent);
>>> child.a;
1
>>> child.hasOwnProperty(a);
false
Abuzer / Software Engineer
Wrapping Up
• Objects
• Functions
• Prototype
• Constructors
• Class
• Inheritance
Abuzer / Software Engineer