The document discusses object-oriented programming concepts in JavaScript. It explains that JavaScript uses prototype-based programming rather than classes. Behavior reuse is accomplished by decorating existing objects that serve as prototypes. It then covers key OO concepts like inheritance, encapsulation, polymorphism, and abstraction and how they are supported in JavaScript through mechanisms like prototypes, functions, and object literals. The document provides examples of defining classes with functions, creating objects, adding methods, and implementing inheritance through the prototype chain. It also discusses namespaces, closures, and other JavaScript programming patterns.
2. Agenda JavaScript you need to know OO in JavaScript OO basics Inheritance Encapsulation Polymorphism 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
3. 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.
4. 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
5. 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
6. Abstraction Abstraction key concept that underpins the very notion of objects - that they abstract the details of their own implementation. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects
7. 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.
8. Polymorphism function 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);
9. 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
10. The Class function 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));
11. 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)
12. The Object You can also create instance of the Class function Bird() { alert(“bird created”); } var crow= new Bird(); varcannary= new Bird(); The constructor is called each time the instance is created
13. The Object Creating 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;
14. The Object object hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in objects
15. The Object Accessing 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 properties ride["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
16. Object Literals (JSON) 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; varrideJSON = { 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' } }; 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
17. JSON : Rules for definition { "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" } ] } { defines start of a an object. } defines the end. [ defines start of an array. ] defines the end. Name and values are separated by :
18. Summary so far A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using new Object() object literals instantiating a “class” Top-level variables are properties of window. all of the following statements are equivalent: varfoo = bar; and window.foo = bar; and foo = bar;
19. 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!'); }
22. 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
23. Function Context Function context describes the object that’s referenced by the this pointer 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 the invocation of f.
24. Anonymous Functions Declaring 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 costly Should be typically used when system does a call – like windows.onload When you are going to call, typically named functions are used
25. 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
26. 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());
27. 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 vartweety = new Canary(); alert("Feet : " + tweety.feet + " Color : " + tweety.color + " Feathers : " + tweety.feathers); function Crow() { this.superclass = Bird; this.superclass(); this.color = "black"; return true; }
28. Inheritance using prototype // define the Person Class function Person() { } Person.prototype.sayHello = function () { alert('hello'); }; // define the Student class function Student() { } // inherit Person Student.prototype = new Person(); // correct the constructor pointer because it points to Person Student.prototype.constructor = Student; // replace the sayHello method Student.prototype.sayHello = function () { alert('hi, I am a student'); } // add sayGoodBye method Student.prototype.sayGoodBye = function () { alert('goodBye'); } var student1 = new Student(); student1.sayHello(); student1.sayGoodBye();
29. 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
30. Namespace example if (typeof com == "undefined") { com = new Object(); } if (typeofcom.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; }
31. 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); });
32. 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
33. Unobtrusive JavaScript What 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); });
34. 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)