// create function to modify its ownfoovariable functiontest ()
{ varfoo = old; }
test(); alert( foo == new );// Globalfoostill equals new
15. Scope
If you forget to use thevar keyword to define a value within a
functioneven if its only used within the functionthe value will be
defined globally.
varfoo = new; alert( foo == new );
// Omitting the var keyword reverts scope // offooto global
level functionbadTest () { foo = bad news; }
badTest(); // Globalfoonow equals bad news alert( foo == bad
news );
16. Scope:Inner Functions
Functions can be defined within one another
Inner functions have access to the outer functions variables
and parameters.
functiongetRandomInt(max) { varrandNum = Math.random() * max;
functionceil() { returnMath.ceil(randNum); } returnceil();// Notice
that no arguments are passed } // Alert random number between 1 and
5 alert(getRandomInt(5));
17. Closures
Inner functions maintain the scope they enjoyed when their
parent function was calledevenafterthe parent function has
terminated.
This allows you to effectively pass variables to functions that
may not be called for some time.
18. Closures
functiondelayedAlert (message, delay) { // Set an enclosed
callback setTimeout(function() { // Usemessagevariable passed to
outer function alert(message); }, delay); }
// Display a message with a 5 second delay
delayedAlert(Refresh, 5000);
19. Context
Your code will always be running within thecontextof another
object
Context is maintained through the use of thethisvariable.
function increment() { this .x =this .x || 0; return this .x++;
};
// Change the context ofset()to the window objectwindow.set =
myObject.set;window.set( Refresh Jacksonville );
alert( myObject.val == Refresh );
alert( window.val == Refresh Jacksonville );
21. Context:Changing Contexts
JavaScript provides two handy functions for executing a
function within the context of another function:
call( )
apply( )
22. Context:Changing Contexts
Usingcall() Arguments passed by name
// Simple function to change the color style of a node
functionchangeColor (newColor) { this .style.color = newColor;
}
// window.changeColor has nostyleproperty, so call fails
changeColor( red );
// Grab the DOM node with the id required varreqField =
document.getElementById( required );
// Call changeColor() within reqFields context
changeColor.call( reqField, red );
23. Context:Changing Contexts
Usingapply() Arguments passed as an array
// Simple function to change the color style of a node
functionchangeColor (newColor) { this .style.color = newColor;
}
// Set the text color of the body element function
setBodyTextColor () { changeColor.apply( document.body,arguments);
}
setBodyTextColor( black );
24.
Constructors and methods
25. Object Oriented Programming
Now lets apply all of this information to a more classical view
of OOP in JavaScript:
Constructors
Object Methods
Public
Private
Privileged
26. About Objects
Almost everything written in JavaScript is an object
Objects can be though of as a collection of propertiesmuch like
ahashin other languages
JavaScript doesnt have a concept of classes like other
object-oriented languages
Classes are simulated using a concept calledprototypal
inheritance
27. Constructors
Like other languages, JavaScript uses thenew operator to create
new instances of objects.
// Create User object constructor functionUser ( name ) { this
.name = name; }
// Create a new instance of a User varme = new User(Bob);
// Alert new users name alert( me.name == Bob );
// Cannot call User directly alert( User.name ==undefined); //
window.name is undefined
28. Methods 29. Public Methods
One way to create a public methoda function that can be freely
reference by code outside your objectis to attach it to the
objectsprototype .
An objectsprototypeis a special property that acts as a base
reference of your object.
Thisprototypeobject is copied and applied to all new instances
of your object.
30. Public Methods
// Our User object written a different way varUser
=function(name) { this .name = name; }
// Add a public accessor method for name User. prototype
.getName = function () { return this .name; }
varme =newUser( Bob );
alert( me.getName() == Bob );
31. Private Methods
Private methods are functions that are only accessible to
methodsinsideyour object and cannot be accessed by external
code.
32. Private Methods
// Our User object with some changes varUser =function(name) {
this .name = name; functionwelcome () { alert( Welcome back, +this
.name + .); } welcome(); }
// Create a new Uservarme =newUser( Bob );// Alerts: Welcome,
Bob.
// Fails because welcome is not a public method
me.welcome();
33. Privileged Methods
The termprivileged methodwas 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
34. Privileged Methods
// Our User object with some tweaks varUser =function(name,
age) { varyear = (new Date()).getFullYear() age; this .getYearBorn
= function () { returnyear; }; };
UsingScope ,Closures ,Contexts , and what weve discussed about
OOP, we can dynamically generate classes based on information
supplied to the constructor.
36. Grand Finale
// Our User object modified to accept an object of properties
functionUser (properties) { // Loop through properties and create
getter and setter methods for(variinproperties ) {function() { this
[get + i] =function() { returnproperties[i]; }; this [set + i]
=function(val) { properties[i] = val; }; })(); } }
// Create a new user, automatically creating get and set
methods varme =newUser( { name: Bob, age: 28 });