Object Oriented JavaScript


Published on

I'm a seasonal JavaScript Programmer. The OO JS was obscure to me when I started. I'm not a geek yet and never would be.... but after read many OO JS articles I got some concept. There is a download link inside the file. I think this would be beneficial for JavaScript Beginners.

Published in: Technology
1 Comment
1 Like
  • I'm a seasonal JavaScript Programmer. The OO JS was obscure to me when I started. I'm not a geek yet and never would be.... but after read many OO JS articles I got some concept. There is a download link inside the file. I think this would be beneficial for JavaScript Beginners.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Object Oriented JavaScript

  1. 1. Munir Hoque<br />Object Oriented JavaScript<br />
  2. 2. <ul><li>Built-in Object data type is the topmost object in JavaScript hierarchy. Please recall your C# or Java Object .
  3. 3. Youcan simply create an object as follow and assign properties as many at any time to the Object. </li></ul>var x = {}; <br />x.a = 15;<br /><ul><li>Let us consider an example :</li></ul>obj = new Object; obj.x = 1;obj.y = 2;<br />This is the scenario of the newly created<br />Object. <br />2<br />Sentrana<br />The JavaScript Object<br />
  4. 4. What did I just see ? I created an Object called obj.<br />But where did the additional object “Prototype” <br />come from ? Well, I’ll discus abut the “Prototype” <br />later. But for now, please keep in mind – <br />Every time an object is created an additional object “Prototype” along with it’s property “constructor” will be created automatically.<br />3<br />Sentrana<br />The JavaScript Object (cont…)<br />
  5. 5. <ul><li>A function in JavaScript is considered as a class.
  6. 6. When a function is called with the newoperator, the function serves as the constructor for that class.
  7. 7. Let’s have a look to the code snippet defines a new class, Foo, and then creates a single object of that class – </li></ul>function Foo() {     this.x = 1;     this.y = 2; }  obj = new Foo();<br />Inside the constructor, the variable this is initialized to point to the just created Object.<br />4<br />Sentrana<br />The Amazing JavaScript Function<br />
  8. 8. Do you want to check our newly created object ?<br />Well, add an property to our newly created object obj.<br />obj.c = 100;<br /> alert(obj.c); // Outputs 100 <br />As I said earlier in javascript you can assign properties at any time to the Object. So, our obj.c = 100; statement is lawfully correct.<br />Caveat : <br />The property “c” we just added to the objwill be visible just within the object. If we create another object of Foonamed obj1and try to access the “c” property we would not get it.<br />obj1 = new Foo(); <br /> alert(obj1.c) // undefined.<br />It is a common pitfall for mainstream programmers form C++/JAVA/C#. Please recall , an object inn JavaScript can add its property any time. An object in JavaScript is any unordered collection of key-value pairs. If its not a primitive (undefined, null, boolean, number or string) its an object.<br />If we want to add an property/method in Foo, that will be available to all the objects, we should use “prototype”. say we want to add a property named “c” to the Fooclass then we will write …..<br />Foo.prototype.c = 100;<br />5<br />Sentrana<br />The Amazing JavaScript Function(Cont…)<br />
  9. 9. <ul><li>A prototype is an object from which other objects inherit properties and methods.
  10. 10. Every object has a prototype by default. Since prototypes are themselves objects, every </li></ul>prototype has a prototype too. (There is only one exception, the default object prototype at the top of <br />every prototype chain. More on prototype chains later).<br /><ul><li>Each object is associated with a prototype which comes from the constructor function from which it is created.
  11. 11. Constructors provide a convenient cross-browser mechanism for assigning a common prototype on instance creation.</li></ul>(Don’t get confused, I’m going to uncover all the mysteries about prototype in the upcoming sections.)<br />6<br />Sentrana<br />What is a Prototype ? <br />
  12. 12. <ul><li>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.</li></ul>Please consider the code snippet – <br />function A()<br /> {<br />this.inA = 2;;<br /> }<br />A.prototype.inAProto = 3;<br />var o = new A();<br /> alert(o.inAProto); // Outputs 3 <br />Here ,when we access the “inAProto” property , JavaScript first looks “inAProto” in “A”. When it does not found “inAProto” in “A” it make a search to the “prototype” and get the property as expected.<br />7<br />Sentrana<br />Prototype in Action<br />o<br />inA<br />2<br />A.prototype<br />constructor<br />A<br />3<br />inAProto<br />
  13. 13. We can assign a function to a class in the same manner as we assign a property in it using the prototype.<br />function Foo() {      this.x = 1; } Foo.prototype.AddX = function(y)    // Define Method {     this.x += y; } obj = new Foo; obj.AddX(5);                        // Call Method<br />8<br />Sentrana<br />Prototype in Action (Cont..)<br />
  14. 14. Please do not think this slide is incoherent. For better understanding about OO nature of JS I would like to introduce you with those.<br />Consider the code snippet – <br />var x = 10;function f(){    alert(this.x); // Outputs 10.}f();<br />Here, f() uses the this keyword to reference x, but notice we don't invoke the function through an instance of an object. So what object does thisreference? this will reference the global object. The global object is where we defined the variable x.<br />Now consider the next code snippet : <br />var x = 10;<br />function f()<br />{<br />this.x = 50;<br />alert(this.x ); // Outputs 50 , because this refer to the current object . Here the current object is a.<br />}<br />var a = f();<br />9<br />Sentrana<br />this & call()<br />
  15. 15. Using the call() are method we can use to assign the this pointer for the duration of a method invocation. As an example, here is how we could use the call() method: <br />var x = 10;var o = { x: 15 };function f(){    alert(this.x);}f(); // Outputs 10f.call(o); // Outputs 15<br />The first invocation of f()will display the value of 10, because this references the global object. The second invocation (via the call method) however, will display the value 15. 15 is the value of the x property inside object o. The call()method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words - we've told the runtime what object to reference asthiswhile executing inside of functionf(). <br />10<br />Sentrana<br />this & call() (Cont..)<br />
  16. 16. <ul><li>There is an explicit concept of the class hierarchy. i.e. Every class can have a super class from which it inherits properties and methods. Any class can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. As we have seen, JavaScript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways.
  17. 17. The standard paradigm, is to use the prototype chain to implement the inheritance of methods from a super class. Any methods defined on the sub-class will supersede those defined on the super-class.</li></ul>Say we have a function named “A“. Now we want to create a subclass of “A“ named “B”. To do this we have to add B” ‘s prototype with “A“ ‘s object ,<br />B.prototype = new A();<br /><ul><li>Something to keep in mind is that each time a sub-class is defined, we explicitly call the constructor of the super-class in order to insert it into our prototype chain. So it is important to ensure that no undesirable side-effects will occur when this call is made. Conversely, if the super-class constructor should be called for each instance of every sub-class, code must be explicitly added to the sub-class's constructor to make this call . </li></ul>A.call(this,[argumentList……….])<br />11<br />Sentrana<br />Prototype and Inheritence<br />
  18. 18. Consider the code snippet – <br />function A()                        // Define super class{    this.x = 1;} A.prototype.DoIt = function()        // Define Method{    this.x += 1;} B.prototype = new A;                // Define sub-classB.prototype.constructor = B;function B(){    A.call(this);                    // Call super-class constructor     this.y = 2;} B.prototype.DoIt = function()        // Define Method{    A.prototype.DoIt.call(this);    // Call super-class method     this.y += 1;} b = new B; document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>'); // Outputs true, trueb.DoIt();document.write(b.x + ', ' + b.y); // Outputs 2,3<br />12<br />Sentrana<br />Prototype and Inheritence (Cont...)<br />
  19. 19. Public Member Variables & Functions :<br /><ul><li>Public functions and variables are available to access on an instance of a class. We can create public member variables and functions using “this” keyword – </li></ul>function Kid (name)<br /> {// Public <br /> this.name = name;<br />this.getName = function () { return this.name; }; <br /> }<br />Private Member Variables :<br /><ul><li>As we learned JavaScript scope, by declaring a variable within a function, it is only available from within there. Private member functions and variables are hidden to outside code. Only public functions can access them. We can create a public variable /method by using the var keyword inside the constructor function.</li></ul> function Kid (name) <br /> { // Private <br />var idol = "Paris Hilton"; <br /> }<br />13<br />Sentrana<br />Access modifiers<br />
  20. 20. Privileged method:<br />A privileged method is a method having access to private properties, but at the same time publicly exposing itself .You can delete or replace a privileged method, but you cannot alter its contents. I.e. this privileged method returns the value of a private property:<br />function Kid (name) <br />{ <br /> // Private <br />var idol = "Paris Hilton"; <br />// Privileged <br />this.getIdol = function ()<br /> {<br /> return idol;<br /> }<br /> }<br />14<br />Sentrana<br />Access modifiers (Cont..)<br />
  21. 21. static property:<br /><ul><li>A static member is shared by all instances of the class as well as the class itself (i.e. the Kid object), but it is only stored in one place. This means that its value is not inherited down to the object’s instances:</li></ul>Kid (name) <br /> {<br /> //Static property <br />Kid.town = "South Park";<br />}<br />15<br />Sentrana<br />Access modifiers (Cont..)<br />
  22. 22. After gathering some skills on OO JavaScript I had developed a sample project that covers all the discussed area of this presentation. It is very easy to understand and may be very helpful for understanding the features of OOP JavaScript.<br />Download the complete project from here - http://hotfile.com/dl/130755893/b52f2ef/OOPJS.rar.html<br />16<br />Sentrana<br />My Experience and a Sample Project<br />
  23. 23. http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/<br />http://mckoss.com/jscript/object.htm<br />http://robertnyman.com/2008/10/14/javascript-how-to-get-private-privileged-public-and-static-members-properties-and-methods/<br />17<br />Sentrana<br />I am Gretful to :<br />
  24. 24. 18<br />Sentrana<br />Question & Answers<br />