oo javascript

40
OBJECT ORIENTED JAVASCRIPT Rody Middelkoop - WT Thursday, March 18, 2010

Upload: rody-middelkoop

Post on 10-May-2015

1.758 views

Category:

Technology


1 download

DESCRIPTION

Slides used for the course WebTechnology, part of CRIA.

TRANSCRIPT

Page 1: OO JavaScript

OBJECT ORIENTED JAVASCRIPT

Rody Middelkoop - WT

Thursday, March 18, 2010

Page 2: OO JavaScript

CRIA-WT - Rody Middelkoop

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 languagesJavaScript doesn’t have a concept of classes like other

object-oriented languagesClasses are simulated using a concept called

prototypal inheritance

2

Thursday, March 18, 2010

Page 3: OO JavaScript

OBJECTSThursday, March 18, 2010

Page 4: OO JavaScript

CRIA-WT - Rody Middelkoop

Object Literal Notation4

// The old wayvar myObject = new Object();myObject.val = “test”;

// Using object literal notationvar myObject = {  val: “test”};

Thursday, March 18, 2010

Page 5: OO JavaScript

CRIA-WT - Rody Middelkoop

Object Literal Notation5

// The old wayvar myArray = new Array(1, 30, “Refresh”);

// Using object literal notationvar myArray = [1, 30, “Refresh”];

Thursday, March 18, 2010

Page 6: OO JavaScript

CRIA-WT - Rody Middelkoop

Anonymous Functions6

// Using an anonymous function as an argumentsetTimeout( function () { alert( “Refresh” );

 }, 1000);  // Using a function as a variablevar myFunc = function () {  alert( “Refresh” ); 

};setTimeout(myFunc, 1000);

Thursday, March 18, 2010

Page 7: OO JavaScript

CRIA-WT - Rody Middelkoop

Binary Assignment7

Set a default value only if the variable doesn’t have a value yet

// Traditional ternary assignmentvar myVar = myVar ? myVar : 0;

// Binary assignmentvar myVar = myVal || 0;

Thursday, March 18, 2010

Page 8: OO JavaScript

INNER FUNCTIONSThursday, March 18, 2010

Page 9: OO JavaScript

CRIA-WT - Rody Middelkoop

Scope: Inner Functions

Functions can be defined within one another Inner 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(getRandomInt(5));

9

Thursday, March 18, 2010

Page 10: OO JavaScript

CRIA-WT - Rody Middelkoop

Closures

Inner functions maintain the scope they enjoyed when their 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.

10

Thursday, March 18, 2010

Page 11: OO JavaScript

CRIA-WT - Rody Middelkoop

Closures11

function delayedAlert (message, delay) {  setTimeout( function () {    alert(message);  }, delay);

} // Display a message with a 5 second delaydelayedAlert(“Refresh”, 5000);

Thursday, March 18, 2010

Page 12: OO JavaScript

OBJECTORIENTED PROGRAMMING

Now let’s apply all of this information to a more classical view of OOP in JavaScript:

Constructors Object Methods

PublicPrivatePrivileged

Thursday, March 18, 2010

Page 13: OO JavaScript

METHODSThursday, March 18, 2010

Page 14: OO JavaScript

CRIA-WT - Rody Middelkoop

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.

14

Thursday, March 18, 2010

Page 15: OO JavaScript

PROTOTYPE…Thursday, March 18, 2010

Page 16: OO JavaScript

CRIA-WT - Rody Middelkoop

Public methods16

var Person = function(name) { this.name = name;};Person.prototype.say = function(){ return this.name;};

var rody = new Person(“Rody”)rody.say()var kris = new Person(“Kris”)kris.say()

Thursday, March 18, 2010

Page 17: OO JavaScript

CRIA-WT - Rody Middelkoop

Prototype

Each function object has a property called prototype, which itself is an object and is initialized when function object is created

Can be removed, replaced, modified dynamically at runtime if internally allowed

Prototype is used to carry the shared state (data, method, etc.) among objects and also plays a role in inheritance of JavaScript

Reference:http://en.wikipedia.org/wiki/Prototype_pattern

17

Thursday, March 18, 2010

Page 18: OO JavaScript

CRIA-WT - Rody Middelkoop

Prototype usage

say() is a property of the prototype objectbut it behaves as if it's a property of the dude object

can we tell the difference?

18

Thursday, March 18, 2010

Page 19: OO JavaScript

CRIA-WT - Rody Middelkoop

Own properties vs. prototype’s19

>>> dude.hasOwnProperty('name');true>>> dude.hasOwnProperty('say');false

Thursday, March 18, 2010

Page 20: OO JavaScript

CRIA-WT - Rody Middelkoop

Private Methods

Private methods are functions that are only accessible to methods inside your object and cannot be accessed by external code.

20

Thursday, March 18, 2010

Page 21: OO JavaScript

CRIA-WT - Rody Middelkoop

Private Methods21

var User = function (name) {  this.name = name;

  function welcome () {    alert( “Welcome back, ” + name + “.”);  }

  welcome();}

var me = new User( “Bob” );  me.welcome();

Thursday, March 18, 2010

Page 22: OO JavaScript

CRIA-WT - Rody Middelkoop

“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

objectThey are also publicly accessible

22

Thursday, March 18, 2010

Page 23: OO JavaScript

CRIA-WT - Rody Middelkoop

“Privileged” Methods23

var User = function (name, age) {  var year = (new Date()).getFullYear()                – age;

  this.getYearBorn = function () {    return year;  };

};

var me = new User( “Bob”, 28 );alert(me.getYearBorn());

Thursday, March 18, 2010

Page 24: OO JavaScript

CONSTRUCTORSThursday, March 18, 2010

Page 25: OO JavaScript

CRIA-WT - Rody Middelkoop

Constructor functions25

var Person = function(name) { this.name = name; this.getName = function() { return this.name; };};

var rody = new Person(“Rody”);alert(rody.getName())

Thursday, March 18, 2010

Page 26: OO JavaScript

CRIA-WT - Rody Middelkoop

A naming convention

MyConstructormyFunction

26

Thursday, March 18, 2010

Page 27: OO JavaScript

INHERITANCEThursday, March 18, 2010

Page 28: OO JavaScript

CRIA-WT - Rody Middelkoop

Parent constructor28

function NormalObject() { this.name = 'normal'; this.getName = function() { return this.name; };}

Thursday, March 18, 2010

Page 29: OO JavaScript

CRIA-WT - Rody Middelkoop

Child constructor29

function PreciousObject(){ this.shiny = true; this.round = true; }

Thursday, March 18, 2010

Page 30: OO JavaScript

CRIA-WT - Rody Middelkoop

The inheritance30

PreciousObject.prototype = new NormalObject();

Thursday, March 18, 2010

Page 31: OO JavaScript

CRIA-WT - Rody Middelkoop

A child object31

var crystal_ball = new PreciousObject();crystal_ball.name = 'Crystal';

crystal_ball.round; // truecrystal_ball.getName(); // "Crystal"

Thursday, March 18, 2010

Page 32: OO JavaScript

CRIA-WT - Rody Middelkoop

Calling the superclass’ constructor32

Thursday, March 18, 2010

Page 33: OO JavaScript

INHERITANCE BY COPYINGThursday, March 18, 2010

Page 34: OO JavaScript

CRIA-WT - Rody Middelkoop

Two objects34

var shiny = { shiny: true, round: true }; var normal = { name: 'name me', getName: function() { return this.name; }};

Thursday, March 18, 2010

Page 35: OO JavaScript

CRIA-WT - Rody Middelkoop

extend()35

function extend(parent, child) { for (var i in parent) { child[i] = parent[i]; } }

Thursday, March 18, 2010

Page 36: OO JavaScript

CRIA-WT - Rody Middelkoop

Inheritance36

extend(normal, shiny);shiny.getName(); // "name me"

Thursday, March 18, 2010

Page 37: OO JavaScript

CRIA-WT - Rody Middelkoop

Grand Finale

Using Scope, Closures, Contexts, and what we’ve discussed about OOP, we can dynamically generate classes based on information supplied to the constructor.

37

Thursday, March 18, 2010

Page 38: OO JavaScript

CRIA-WT - Rody Middelkoop

Grand Finale38

function User (properties) {  for ( var i in properties ) { function () {    this[“get” + i] = function () {       return properties[i];    };    this[“set” + i] = function (val) {       properties[i] = val;    };

  })(); }}

var me = new User( {  name: “Bob”,  age: 28

});Thursday, March 18, 2010

Page 39: OO JavaScript

CRIA-WT - Rody Middelkoop

Grand Finale39

// …continued

alert( me.name == null );alert( me.getname() == “Bob” );me.setage(21);alert( me.getage() == 21 );

Thursday, March 18, 2010