39
Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008

Object Oriented JavaScript

Embed Size (px)

DESCRIPTION

An overview of object-oriented programming concepts in JavaScript.

Citation preview

  • 1. Getting from Scripts to Applications Donald J. Sipe|Refresh Jacksonville|November 11 th2008

2. JavaScript

  • We are here

Pseudoclassical Inheritance Hello World! 3. JavaScript

  • What well be talking about
  • OOP Basics
  • Scope
  • Closures
  • Context
  • Appling to OOP
  • Constructors
  • Methods
    • Public
    • Private
    • Privileged

4. But First... Some handy tools

  • Here are some handy things you might not know JavaScript can do:
  • Object-literal notation
  • Anonymous functions
  • Binary assignment
  • Dot-styleandarray-style access of properties

5. Handy Tools

  • Object Literal Notation Makes JSON possible
  • // The old way varmyObject = new Object(); myObject.val = test;
  • // Using object literal notation varmyObject = { val: test };

6. Handy Tools

  • Object Literal Notation
  • // The old way varmyArray = new Array(1, 30, Refresh);
  • // Using object literal notation varmyArray = [1, 30, Refresh];

7. Handy Tools

  • Anonymous Functions
  • In JavaScript, functions are treated as values, which means:
    • Functions can be assigned to variables
    • Functions can be passed as arguments to other functions

8. Handy Tools

  • Anonymous Functions
  • // Using an anonymous function as an argument setTimeout(function() { alert( Refresh ); }, 1000 );
  • // Using a function as a variable varmyFunc =function() {alert( Refresh );}; setTimeout(myFunc, 1000);

9. Handy Tools

  • Anonymous Functions : Building a scope bubble Using an anonymous function to wrap code you dont want in the global scope
  • varglobalVar = Refresh;// Global scope
  • // Create a scope bubble (function() { varprivateVar = Jacksonville; alert( globalVar + + privateVar ); } )();
  • alert (privateVar ==undefined );

10. Handy Tools

  • Binary Assignment Set a default value only if the variable doesnt have a value yet
  • // Traditional ternary assignment varmyVar = myVar?myVar:0;
  • // Binary assignment varmyVar = myVal || 0;

11. Handy Tools

  • Dot-Style and Array-Style property access
  • varsampleObj = { color: blue, width: 16px };
  • // Traditional dot-style access alert( sampleObj.color == blue );
  • // Alternative array-style access alert( sampleObj[width] == 16px );

12.

  • Scope, Closures, and Context

13. Scope

  • Only functions have scope.Blocks ( if ,while ,for ,switch ) do not.
  • All variables are within the global scope unless they are defined within afunction .
  • All global variables actually become properties of thewindow object
  • When variables arenotdeclared using thevar keyword, they decared globally.

14. Scope

  • varfoo = orig;//foois now a global variable
  • if( true ) { foo = new;// Globalfoonow equals new }
  • // 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++; };
  • alert( increment() == 0 );
  • alert( increment() == 1 );

20. Context

  • varmyObject = { set:function(newVal) {this .val = newVal; } };
  • alert( myObject.val ==null);//valproperty not set yet
  • myObject.set(Refresh); alert( myObject.val == Refresh ); //valequals Refresh
  • // 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; }; };
  • // Create a new Uservarme =newUser( Bob, 28 );
  • // Access privileged method to access privateyearvalue alert( me.getYearBorn() == 1980 );
  • // Fails becauseyearis private alert( me.year == null );

35. Grand Finale

  • 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 });

37. Grand Finale

  • // continued
  • // Note thatnameis private withinproperties alert( me.name ==null);
  • // Access privilegedgetname()method alert( me.getname() == Bob );
  • // Use the dynamically generated setter// to change the users age me.setage(21); alert( me.getage() == 21 );

38. 39. References

  • Pro JavaScript Techniques, by John Resig
  • Douglas Crockfords
  • YUI Theater Presentations
  • http://developer.yahoo.com/yui/theater