oo in javascript

36
OO IN JAVASCRIPT Gunjan Kumar

Upload: gunjan-kumar

Post on 10-May-2015

1.548 views

Category:

Technology


0 download

DESCRIPTION

Introduction to OO in JavaScript

TRANSCRIPT

Page 1: OO in JavaScript

OO IN JAVASCRIPT

Gunjan Kumar

Page 2: OO in JavaScript

Agenda

JavaScript you need to know OO in JavaScript

○ OO basics InheritanceEncapsulationPolymorphism

○ Class○ Object and properties○ Object literals (JSON)○ Functions and function context,○ Anonymous functions○ Prototype and inheritance○ Closure

unobtrusive JavaScript - the way our code should be structured

Page 3: OO in JavaScript

OO in JS Prototype-based programming is a style of object-oriented

programming in which classes are not present behavior reuse (inheritance) is accomplished through a process

of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented,

or instance-based programming. Support in JS :

Inheritance - The ability to define the behavior of one object in terms of another by sub-classing.

Encapsulation - Support for method calls on a JavaScript object as a member of a Class

Polymorphism - The ability for two classes to respond to the same (collection of) methods.

Page 4: OO in JavaScript

Inheritance Inheritance

allows one class to replicate and extend the functionality of another without having to re-implement the existing class’s behavior

JavaScript only supports single class inheritance Supported by prototype and other options in JS More details later in the slides

Page 5: OO in JavaScript

Encapsulation Encapsulation

ensures that an object’s state can only be changed by the object itself, as a result of that object’s performing one of the operations (methods) it supports.

Supported by defining variables in function with this. And then defining functions to access these variables

function A(){ var x = 7; this.GetX = function () { return x; } this.SetX = function (xT) { x = xT; } } obj = new A; obj2 = new A; document.write(obj.GetX() + ' ' + obj2.GetX());

obj.SetX(14); document.write(' ' + obj.GetX() + ' ' + obj2.GetX());

//alert(obj.x);//gives undefined

Encapsulation.htm

Page 6: OO in JavaScript

Polymorphism Polymorphism

ability to appear in different forms. allows an object of a given class to be treated as if it were an

object of its superclass, despite the fact that one or more of the superclass’s methods may be defined differently (overridden) in

the object’s true class. In JS, different classes can define methods with the same name;

methods are scoped to the class in which they're defined. Achieved by simply having different object classes implement a

collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.

Page 7: OO in JavaScript

Polymorphismfunction A() { this.x = 1; } A.prototype.DoIt = function() // Define Method { this.x += 1; } function B() { this.x = 1; } B.prototype.DoIt = function() // Define Method { this.x += 2; } a = new A; b = new B; a.DoIt(); b.DoIt(); document.write(a.x + ', ' + b.x);

Polymorphism.htm

Page 8: OO in JavaScript

The Class JavaScript is a prototype-based language which

contains no class statement, such as is found in C++ or Java.

This is of relevance ONLY if we expect multiple objects with same properties – thus reducing the lines of code

No formal way to define a class. Any function definition is a class Properties and methods can be defined within the function

To instantiate, we use the new keyword We can define the function to accept parameters to

simulate a constructor which sets default params

Page 9: OO in JavaScript

The Classfunction Owner(_name, _age) { this.name = _name; this.age = _age; }

function Bike(_name, _model, _make, _mileage, _owner) { this.name = _name; this.model = _model; this.make = _make; this.mileage = _mileage; this.owner = _owner; this.whatAmI = function () { return this.year + ' ' + this.make + ' ' + this.model; } }

var bike3 = new Bike('Yamaha3', 'Model 3', new Date(2008, 3, 12), 33, new Owner('owner 3', 33));

Objects in JS.htm

Page 10: OO in JavaScript

The Object

Create object by new Object() No properties by default. Keep adding dynamically. primary purpose of an Object instance to serve as a container for a

named collection of other objects The name of a property is a string Value can be any JavaScript object, be it a Number, String, Date, Array,

basic Object, or any other JavaScript object type (including functions)

OO Basics.htm

Page 11: OO in JavaScript

The Object You can also create instance of the Class

function Bird() {

alert(“bird created”);

}

var crow= new Bird();

var cannary= new Bird(); The constructor is called each time the instance is created

Page 12: OO in JavaScript

The ObjectCreating and populating an object

var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12);

var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;

Page 13: OO in JavaScript

The Object

object hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in objects

Page 14: OO in JavaScript

The ObjectAccessing values from object

$(document).ready(function () { $(".container").append("<tr><td>Make</td><td>" + ride.make + "</td></tr>"); $(".container").append("<tr><td>Model</td><td>" + ride.model + "</td></tr>"); $(".container").append("<tr><td>Year</td><td>" + ride.year + "</td></tr>"); $(".container").append("<tr><td>Purchased</td><td>" + ride.purchased + "</td></tr>"); $(".container").append("<tr><td>Owner Name</td><td>" + ride.owner.name + "</td></tr>"); $(".container").append("<tr><td>Owner Occupation</td><td>" + ride.owner.occupation + "</td></tr>"); });

Another way of accessing propertiesride["Clumsy Property"] = 'Really clumsy value'; $(".container").append("<tr><td>Clumsy Value</td><td>" + ride["Clumsy Property"] + "</td></tr>");

This is useful for names that have spaces / (.) dots

Page 15: OO in JavaScript

Object Literals (JSON) var rideJSON = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005, 3, 12), 'Clumsy Property' : 'Really clumsy value', owner: { name: 'Spike Spiegel', occupation: 'bounty hunter' } };

var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12); ride["Clumsy Property"] = 'Really clumsy value'; var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;

JavaScript Object Notation allows us to define object using literals- we no longer need to instantiate new Object()- reduces the work of defining name and then assigning value

Page 16: OO in JavaScript

JSON : Rules for definition { defines start of a an

object. } defines the end. [ defines start of an

array. ] defines the end. Name and values are

separated by :

{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }

Page 17: OO in JavaScript

Functions

Similar to any other type Function instances are values that can be assigned to variables,

properties, or parameters just like instances of other object types Following are the same :

○ function hello(){ alert('Hi there!'); } ○ hello = function(){ alert('Hi there!'); }○ window.hello = function(){ alert('Hi there!'); }

Page 18: OO in JavaScript

Functions : adding as property

var ride = {make: 'Yamaha',model: 'V-Star Silverado 1100',year: 2005,purchased: new Date(2005,3,12),owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'},whatAmI: function() {

return this.year+' '+this.make+' '+this.model;}};

Page 19: OO in JavaScript

Functions contd.

Page 20: OO in JavaScript

Functions contd.

Functions can be passed as parameter

setTimeout(function() { alert('Hi there!'); },5000);

Context in function object referenced by this—termed the function context In the default case, the context (this) of an invocation of the

function is the object whose property contains the reference used to invoke the function

If you are using call(), you can specify the context and params

Page 21: OO in JavaScript

Function ContextFunction context describes the object that’s referenced by the thispointer during the invocation of a function. var o1 = {handle:'o1'}; var o2 = {handle:'o2'}; var o3 = {handle:'o3'}; window.handle = 'window';

function whoAmI(messageText) { return this.handle + " , message text : " + messageText; } o1.identifyMe = whoAmI; alert(whoAmI("message text window")); alert(o1.identifyMe("message text o1")); alert(whoAmI.call(o2, "message text o2")); alert(whoAmI.apply(o3, "message text o3"));

A function f acts as a method of object o when o serves as the function context of theinvocation of f.

Function Context.htm

Page 22: OO in JavaScript

Anonymous FunctionsDeclaring functions inline rather than separately IF IT IS USED ONLY ONCE.

var employee2 = { empID: 57, firstName: 'Gunjan', lastName: 'Kumar', whoAmI: function () { return "Emp ID : " + this.empID + " First Name : " + this.firstName + " Last Name : " + this.lastName; } };

These are faster since name resolution is costlyShould be typically used when system does a call – like windows.onload

When you are going to call, typically named functions are used

Anonymous functions.htm

Page 23: OO in JavaScript

Prototype Allows you to add new properties / methods to class Helps in implementing inheritance of sorts – you can

instantiate objects of older type and then add additional properties to the “class”

Advantages You can add methods to “classes” you didn’t create the functions are only stored once (in the prototype object), rather

than in every new object

When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype

Page 24: OO in JavaScript

Prototype example String.prototype.convertUnderscores = function () { return this.replace(/_/g, " "); }; var underscored = "Are_there_any_spaces_in_here?"; var spaced = underscored.convertUnderscores(); alert(spaced);

function Bird() { this.feet = 2; this.feathers = true; return true; } var bird1 = new Bird(); alert(bird1.getFeetNum); Bird.prototype.getFeetNum = function () { return this.feet; }; var bird2 = new Bird(); alert(bird2.getFeetNum());

Prototype.htm

Page 25: OO in JavaScript

Inheritance using prototype function Bird() {

this.feet = 2; this.feathers = true; return true; } function Canary() { this.color = "yellow"; return true; } Canary.prototype = new Bird(); //defining parent class if you will var tweety = new Canary(); alert("Feet : " + tweety.feet +

" Color : " + tweety.color +" Feathers : " + tweety.feathers);

function Crow() { this.superclass = Bird; this.superclass(); this.color = "black"; return true; }

Inheritance.htm

Page 26: OO in JavaScript

Inheritance using prototype

Inheritance2.htm

// define the Person Class function Person() { } Person.prototype.sayHello = function () { alert('hello'); };

// define the Student classfunction Student() { }// inherit PersonStudent.prototype = new Person();// correct the constructor pointer because it points to PersonStudent.prototype.constructor = Student;// replace the sayHello methodStudent.prototype.sayHello = function () { alert('hi, I am a student'); }// add sayGoodBye methodStudent.prototype.sayGoodBye = function () { alert('goodBye'); }

var student1 = new Student();student1.sayHello();student1.sayGoodBye();

Page 27: OO in JavaScript

Namespace

No inherent way to prevent name conflict – if 2 people define same named “class”, the later definition will be used.

Namespace is implemented by typically using domain names with the class name BUT that implies each part of the Domain Name has to be defined

Page 28: OO in JavaScript

Namespace exampleif (typeof com == "undefined") { com = new Object(); } if (typeof com.qwest == "undefined") { com.qwest = new Object(); } com.qwest.Bird = function() { this.feet = 2; this.feathers = true; this.color = "yellow"; return true; }

Bird = function () { this.feet = 2; this.feathers = true; this.color = "black"; return true; }

Namespace.htm

Page 29: OO in JavaScript

Closure

Closure is a Function instance coupled with the local variables from its environment that are necessary for its execution.

How this manifests : For a function, a variable defined in its scope at the point of declaration, is carried along with the function even after the point of declaration has gone out of scope, closing the declaration

$(function () { var local = 1; window.setInterval(function () { $('#display') .append('<div>At ' + new Date() + ' local=' + local + '</div>'); local++; }, 3000); });

Page 30: OO in JavaScript

Closure contd.

Another important feature of closures is that a function context is never included as part of the closure.

this.id = 'someID';$('*').each(function(){alert(this.id);});

Here this.id will give the id property for the function context of each which is NOT same as the one with someID

this.id = 'someID';var outer = this;$('*').each(function(){alert(outer.id);});

Here , the variable outer is defined in the scope of the function and hence by closure, it can access the same

Page 31: OO in JavaScript

Unobtrusive JavaScriptWhat is it?

Not a formal term but refers to an approach on how to use JavaScript in web pages

Primarily talks about separation of behavior from presentation (sounds familiar??)

<input type="text" name="date" onchange="validateDate()" />

Vs.

<input type="text" name="date" id="date" />

$(function(){

$('#date').bind('change', validateDate);

});

Page 32: OO in JavaScript

Unobtrusive JavaScript (contd.)

purpose of markup is to describe a structure combining the structure and behavior negatively impacts

maintainability inline event handlers are harder to use and maintain

specially when one needs to set handlers for several events on a single element when one wants to set the same event handler on several elements when one is using event delegation

In essence, this is asking for a separate .JS file that contains all the behavior and attaches the same to markup.

Typically this would result in three set of files Html (markup) CSS (presentation) JS (behavior)

Page 33: OO in JavaScript

Unobtrusive JavaScript Reference

Reference : http://en.wikipedia.org/wiki/Unobtrusive_JavaScript http://icant.co.uk/articles/seven-rules-of-unobtrusive-

javascript/ http://www.onlinetools.org/articles/unobtrusivejavascript/

chapter1.html http://labs.adobe.com/technologies/spry/articles/

best_practices/separating_behavior.html

Page 34: OO in JavaScript

JSON References http://en.wikipedia.org/wiki/JSON http://www.json.org/ http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScrip

t_Object_Notation_) http://www.jsonlint.com/ : this allows you to validate / format

json string https://github.com/douglascrockford/JSON-js

var myJSONText = JSON.stringify(myObject)

var myObject = JSON.parse(myJSONtext)

http://api.jquery.com/jQuery.parseJSON/ http://api.jquery.com/jQuery.getJSON/ var obj = jQuery.parseJSON('{"name":"John"}');

alert( obj.name === "John" );

Page 35: OO in JavaScript

OO Reference

https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

PDFs from earlier training sessions (to be shared)

http://mckoss.com/jscript/object.htm : very nicely explains inheritance, polymorphism and encapsulation in JS

Page 36: OO in JavaScript

Thank You

[email protected]

http://in.linkedin.com/in/gunjankumar300