SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Munir Hoque Object Oriented JavaScript
[object Object]
Youcan simply create an object as follow and assign properties as many at any time to the Object. var  x = {};    x.a = 15; ,[object Object],obj = new Object;            obj.x = 1;obj.y = 2; This is the scenario of the newly created Object.            2 Sentrana The JavaScript Object
What did I just see ? I created an Object called obj. But where did the additional object “Prototype”  come from ? Well, I’ll discus abut the “Prototype”  later. But for now, please keep in mind –  Every time an object is created an additional object “Prototype”  along with it’s property “constructor” will be created automatically. 3 Sentrana The JavaScript Object (cont…)
[object Object]
When a function is called with the newoperator, the function serves as the constructor for that class.
Let’s have a look to the code snippet defines a new class, Foo, and then creates a single object of that class – function Foo()                        	{    	  this.x = 1;    	  this.y = 2;	}        obj = new Foo(); Inside the constructor, the variable this is initialized to point to the just created Object. 4 Sentrana The Amazing JavaScript Function
Do you want to check our newly created object ? Well, add an property to our newly created object  obj. obj.c = 100;                       alert(obj.c);   // Outputs 100  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. Caveat :     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. obj1 = new Foo();                       alert(obj1.c) // undefined. 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. 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 ….. Foo.prototype.c = 100; 5 Sentrana The Amazing JavaScript Function(Cont…)
[object Object]
Every object has a prototype by default. Since prototypes are themselves objects, every prototype has a prototype too. (There is only one exception, the default object prototype at the top of  every prototype chain. More on prototype chains later). ,[object Object]
Constructors provide a convenient cross-browser mechanism for assigning a common prototype on instance creation.(Don’t get confused, I’m going to uncover all the mysteries about prototype in the upcoming sections.) 6 Sentrana What is a Prototype ?
[object Object],Please consider the code snippet –  function A() 		{ this.inA = 2;; 		} A.prototype.inAProto = 3; var o = new A(); 		alert(o.inAProto); // Outputs 3  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. 7 Sentrana Prototype in Action o inA 2 A.prototype constructor A 3 inAProto
We can assign a function to a class in the same manner as we assign a property in it using the prototype. function Foo()	{   	    this.x = 1;   	} Foo.prototype.AddX = function(y)    // Define Method	{    	  this.x += y;	} obj = new Foo; obj.AddX(5);                        // Call Method 8 Sentrana Prototype in Action (Cont..)
Please do not think this slide is incoherent. For better understanding about OO nature of JS I would like to introduce you with those. Consider the code snippet –  var  x  = 10;function f(){    alert(this.x);  // Outputs 10.}f(); 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. Now consider the next code snippet :  var x = 10; function f() { this.x = 50; alert(this.x ); // Outputs 50 , because  this refer to the current object . Here the current object is a. } var a = f(); 9 Sentrana this & call()
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:  var  x  = 10;var o = { x: 15 };function f(){    alert(this.x);}f();       // Outputs 10f.call(o); // Outputs 15 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().  10 Sentrana this & call() (Cont..)
[object Object]
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.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 , B.prototype = new A(); ,[object Object],A.call(this,[argumentList……….]) 11 Sentrana Prototype and Inheritence
Consider the code snippet –  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 12 Sentrana Prototype and Inheritence (Cont...)

Weitere ähnliche Inhalte

Kürzlich hochgeladen

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 

Kürzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 

Empfohlen

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

Object Oriented JavaScript

  • 1. Munir Hoque Object Oriented JavaScript
  • 2.
  • 3.
  • 4. What did I just see ? I created an Object called obj. But where did the additional object “Prototype” come from ? Well, I’ll discus abut the “Prototype” later. But for now, please keep in mind – Every time an object is created an additional object “Prototype” along with it’s property “constructor” will be created automatically. 3 Sentrana The JavaScript Object (cont…)
  • 5.
  • 6. When a function is called with the newoperator, the function serves as the constructor for that class.
  • 7. Let’s have a look to the code snippet defines a new class, Foo, and then creates a single object of that class – function Foo() {     this.x = 1;     this.y = 2; }  obj = new Foo(); Inside the constructor, the variable this is initialized to point to the just created Object. 4 Sentrana The Amazing JavaScript Function
  • 8. Do you want to check our newly created object ? Well, add an property to our newly created object obj. obj.c = 100; alert(obj.c); // Outputs 100 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. Caveat : 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. obj1 = new Foo(); alert(obj1.c) // undefined. 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. 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 ….. Foo.prototype.c = 100; 5 Sentrana The Amazing JavaScript Function(Cont…)
  • 9.
  • 10.
  • 11. Constructors provide a convenient cross-browser mechanism for assigning a common prototype on instance creation.(Don’t get confused, I’m going to uncover all the mysteries about prototype in the upcoming sections.) 6 Sentrana What is a Prototype ?
  • 12.
  • 13. We can assign a function to a class in the same manner as we assign a property in it using the prototype. function Foo() {      this.x = 1; } Foo.prototype.AddX = function(y)    // Define Method {     this.x += y; } obj = new Foo; obj.AddX(5);                        // Call Method 8 Sentrana Prototype in Action (Cont..)
  • 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. Consider the code snippet – var x = 10;function f(){    alert(this.x); // Outputs 10.}f(); 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. Now consider the next code snippet : var x = 10; function f() { this.x = 50; alert(this.x ); // Outputs 50 , because this refer to the current object . Here the current object is a. } var a = f(); 9 Sentrana this & call()
  • 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: var x = 10;var o = { x: 15 };function f(){    alert(this.x);}f(); // Outputs 10f.call(o); // Outputs 15 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(). 10 Sentrana this & call() (Cont..)
  • 16.
  • 17.
  • 18. Consider the code snippet – 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 12 Sentrana Prototype and Inheritence (Cont...)
  • 19.
  • 20. Privileged method: 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: function Kid (name) { // Private var idol = "Paris Hilton"; // Privileged this.getIdol = function () { return idol; } } 14 Sentrana Access modifiers (Cont..)
  • 21.
  • 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. Download the complete project from here - http://hotfile.com/dl/130755893/b52f2ef/OOPJS.rar.html 16 Sentrana My Experience and a Sample Project
  • 24. 18 Sentrana Question & Answers