Similar presentations:
OOP part 1. Object-Oriented JavaScript
1. Object-Oriented JavaScript
2. JavaScript
Hello World!We are here
Pseudoclassical Inheritance
3. JavaScript
What we’ll be talking aboutFunctions
Scope
Closures
Context
Appling to OOP
Constructors
Methods
Public
Private
Privileged
4. Functions
In JavaScript, functions are treated as values, whichmeans:
Functions can be assigned to variables
Functions can be passed as arguments to other functions
5.
// Using an anonymous function as an argumentsetTimeout( function () {
alert( “Refresh” );
}, 1000
);
// Using a function as a variable
var myFunc = function () {
alert( “Refresh” );
};
setTimeout(myFunc, 1000); // Or myFunc();
6. 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 decared globally.
7. Scope
var foo = “orig”;if ( true ) {
foo = “new”;
}
// foo is now a global variable
// Global foo now equals “new”
// create function to modify its own foo variable
function test () {
var foo = “old”;
}
test();
alert( foo == “new” );
// Global foo still equals “new”
8. Scope
If you forget to use the var keyword to define a value within afunction—even if it’s only used within the function—the value
will be defined globally.
var foo = “new”;
alert( foo == “new” );
// Omitting the var keyword reverts scope
// of foo to global level
function badTest () {
foo = “bad news”;
}
badTest();
// Global foo now equals “bad news”
alert( foo == “bad news” );
9. 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));
10. Closures
Inner functions maintain the scope they enjoyed whentheir parent function was called—even after the parent
function has terminated.
This allows you to effectively pass variables to
functions that may not be called for some time.
11. Closures
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);
12. Context
Your code will always be running within the context ofanother object
Context 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 );
13. 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 Jacksonville” );
alert( myObject.val == “Refresh” );
alert( window.val == “Refresh Jacksonville” );
14. Context: Changing Contexts
JavaScript provides two handy functions for executing afunction within the context of another function:
call( )
apply( )
15. Context: Changing Contexts
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” );
16. Context: Changing Contexts
Using apply() — Arguments passed as an array// Simple function to change the color style of a node
function changeColor (newColor) {
this.style.color = newColor;
}
// Set the text color of the body element
function setBodyTextColor () {
changeColor.apply( document.body, arguments );
}
setBodyTextColor( “black” );
17. Object Oriented Programming
Constructors and methods18. Object Oriented Programming
Now let’s apply all of this information to a more classicalview of OOP in JavaScript:
Constructors
Object Methods
Public
Private
Privileged
19. About Objects
Almost everything written in JavaScript is an objectObjects can be though of as a collection of
properties—much like a hash in other languages
JavaScript doesn’t have a concept of classes like other
object-oriented languages
Classes are simulated using a concept called prototypal
inheritance
20. Constructors
Like other languages, JavaScript uses the new operator to createnew instances of objects.
// Create User object constructor
function User ( name ) {
this.name = name;
}
// Create a new instance of a User
var me = new User(“Bob”);
// Alert new user’s name
alert( me.name == “Bob” );
// Cannot call User directly
alert( User.name == undefined ); // window.name is undefined
21. Methods
PrivatePrivileged
Public
22. Public Methods
One way to create a public method—a function that canbe 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.
23. Public Methods
// Our User object written a different wayvar User = function (name) {
this.name = name;
}
// Add a public accessor method for name
User.prototype.getName = function () {
return this.name;
}
var me = new User( “Bob” );
alert( me.getName() == “Bob” );
24. Private Methods
Private methods are functions that are only accessible tomethods inside your object and cannot be accessed by
external code.
25. 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( “Bob” );
// Alerts: “Welcome, Bob.”
// Fails because welcome is not a public method
me.welcome();
26. “Privileged” Methods
The term privileged method was coined by DouglasCrockford. 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
27. “Privileged” Methods
// Our User object with some tweaksvar User = function (name, age) {
var year = (new Date()).getFullYear() – age;
this.getYearBorn = function () {
return year;
};
};
// Create a new User
var me = new User( “Bob”, 28 );
// Access privileged method to access private year value
alert( me.getYearBorn() == 1980 );
// Fails because year is private
alert( me.year == null );