SlideShare a Scribd company logo
1 of 19
Function-and-Prototype Defined
Classes in JavaScript
Hong Langford
June 24, 2017
Overview
• Objects and prototypes
• Student-Grade example
• this keyword
• Constructor function
• How does the new operator work in JavaScript
• Inheritance with the prototype chain
• The instanceof operator in JavaScript
• References
Objects and Prototypes
• Objects are JavaScript’s fundamental data
structure. Intuitively, an object represents a
table relating strings to values. But when you
dig deeper, there is a fair amount of
machinery that goes into objects.
• Like many object-oriented languages,
JavaScript provides support for
implementation inheritance: the reuse of code
or data through a dynamic delegation
mechanism. But unlike many conventional
languages, JavaScript’s inheritance mechanism
is based on prototypes rather than classes. For
many programmers, JavaScript is the
first object-oriented language they encounter
without classes.
• JavaScript classes introduced in ECMAScript
2015 (ES6) are primarily syntactical sugar over
JavaScript's existing prototype-based
inheritance. The class syntax is not introducing
a new object-oriented inheritance model to
JavaScript. JavaScript classes provide a much
simpler and clearer syntax to create objects
and deal with inheritance for programmers
who are used to classes.
• In many languages, every object is an instance
of an associated class, which provides code
shared between all its instances. JavaScript,
by contrast, has no built-in notion of classes.
Instead, objects inherit from other objects.
Every object is associated with some other
object, known as its prototype. Working with
prototypes can be different from classes,
although many concepts from traditional
object-oriented languages still carry over.
Student-Grade Example
function Student(x) {
this.name = x;
this.grade = [];
}
Student.prototype = {
addGrade: function(x) {
this.grade.push(x);
}
};
var Tom = new Student("Tom");
Tom.addGrade(82);
Tom.addGrade(75);
Tom.addGrade(70);
var Sarah = new Student("Sarah");
Sarah.addGrade(83);
Sarah.addGrade(88);
Sarah.addGrade(91);
var Vu = new Student("Vu");
Vu.addGrade(85);
Vu.addGrade(79);
Vu.addGrade(84);
console.log(Tom, Sarah, Vu);
this keyword
• A function's this keyword behaves a little
differently in JavaScript compared to other
languages. In most cases, the value of this is
determined by how a function is called. It may
be different each time the function is called.
Constructor Function
• Constructor function
– A "constructor" in JavaScript is "just" a function
that happens to be called with the new operator.
How does the new operator work in
JavaScript?
• The new operator uses the
internal [[Construct]] method, and it basically
does the following:
– Initializes a new object
– Sets the internal [[Prototype]] of this object, pointing
to the constructor function prototype property.
– If the constructor function's prototype property is
not an object (but a primitive value, such as a
Number, String, Boolean, Undefined or
Null), Object.prototype is used instead.
– After creating the object, it calls the function,
providing the object as its this value.
– If the return value of the called function, is a
primitive, the object created internally is returned.
– Otherwise, if an object is returned, the object
created internally is lost.
• { name: 'Tom', grade: [ 82, 75, 70 ] } { name:
'Sarah', grade: [ 83, 88, 91 ] } { name: 'Vu',
grade: [ 85, 79, 84 ] }
Inheritance with the Prototype Chain
• When it comes to inheritance, JavaScript only has
one construct: objects. Each object has a private
property (referred to as [[Prototype]] ) which
holds a link to another object called
its prototype. That prototype object has a
prototype of its own, and so on until an object is
reached with null as its prototype. By
definition, null has no prototype, and acts as the
final link in this prototype chain.
• Nearly all objects in JavaScript are instances
of Object constructor which sits on the top of
a prototype chain. And the prototype of
Object’s prototype is not pointing anywhere
but just null .
The instanceof operator in JavaScript
• The instanceof operator tests presence
of constructor.prototype in object's prototype
chain.
References
1. David Herman, Effective JavaScript: 68 Specific
Ways to Harness the Power of JavaScript
(Effective Software Development
Series), Addison-Wesley Professional, 1 edition
(December 6, 2012).
2. https://stackoverflow.com/questions/6750880/
how-does-the-new-operator-work-in-javascript
3. https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference
Thank You!

More Related Content

What's hot

4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and MethodsNilesh Dalvi
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercisesagorolabs
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and VariablesNilesh Dalvi
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?RAKESH P
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in ScalaKnoldus Inc.
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 

What's hot (20)

Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercises
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
Scala basic
Scala basicScala basic
Scala basic
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 

Similar to Function-and-prototype defined classes in JavaScript

Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Javascript for Intermediates
Javascript for IntermediatesJavascript for Intermediates
Javascript for IntermediatesAnkit Agrawal
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfSreeVani74
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...MaruMengesha
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
javascript
javascript javascript
javascript Kaya Ota
 
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...Baltasar García Perez-Schofield
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQueryBobby Bryant
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingMH Abid
 

Similar to Function-and-prototype defined classes in JavaScript (20)

Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Java
JavaJava
Java
 
Javascript for Intermediates
Javascript for IntermediatesJavascript for Intermediates
Javascript for Intermediates
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Feb-2021_L1_...
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Viva file
Viva fileViva file
Viva file
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
javascript
javascript javascript
javascript
 
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Traits composition
Traits compositionTraits composition
Traits composition
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Java
JavaJava
Java
 

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

Function-and-prototype defined classes in JavaScript

  • 1. Function-and-Prototype Defined Classes in JavaScript Hong Langford June 24, 2017
  • 2. Overview • Objects and prototypes • Student-Grade example • this keyword • Constructor function • How does the new operator work in JavaScript • Inheritance with the prototype chain • The instanceof operator in JavaScript • References
  • 3. Objects and Prototypes • Objects are JavaScript’s fundamental data structure. Intuitively, an object represents a table relating strings to values. But when you dig deeper, there is a fair amount of machinery that goes into objects.
  • 4. • Like many object-oriented languages, JavaScript provides support for implementation inheritance: the reuse of code or data through a dynamic delegation mechanism. But unlike many conventional languages, JavaScript’s inheritance mechanism is based on prototypes rather than classes. For many programmers, JavaScript is the first object-oriented language they encounter without classes.
  • 5. • JavaScript classes introduced in ECMAScript 2015 (ES6) are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance for programmers who are used to classes.
  • 6. • In many languages, every object is an instance of an associated class, which provides code shared between all its instances. JavaScript, by contrast, has no built-in notion of classes. Instead, objects inherit from other objects. Every object is associated with some other object, known as its prototype. Working with prototypes can be different from classes, although many concepts from traditional object-oriented languages still carry over.
  • 7. Student-Grade Example function Student(x) { this.name = x; this.grade = []; } Student.prototype = { addGrade: function(x) { this.grade.push(x); } }; var Tom = new Student("Tom"); Tom.addGrade(82); Tom.addGrade(75); Tom.addGrade(70);
  • 8. var Sarah = new Student("Sarah"); Sarah.addGrade(83); Sarah.addGrade(88); Sarah.addGrade(91); var Vu = new Student("Vu"); Vu.addGrade(85); Vu.addGrade(79); Vu.addGrade(84); console.log(Tom, Sarah, Vu);
  • 9. this keyword • A function's this keyword behaves a little differently in JavaScript compared to other languages. In most cases, the value of this is determined by how a function is called. It may be different each time the function is called.
  • 10. Constructor Function • Constructor function – A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.
  • 11. How does the new operator work in JavaScript? • The new operator uses the internal [[Construct]] method, and it basically does the following: – Initializes a new object – Sets the internal [[Prototype]] of this object, pointing to the constructor function prototype property. – If the constructor function's prototype property is not an object (but a primitive value, such as a Number, String, Boolean, Undefined or Null), Object.prototype is used instead.
  • 12. – After creating the object, it calls the function, providing the object as its this value. – If the return value of the called function, is a primitive, the object created internally is returned. – Otherwise, if an object is returned, the object created internally is lost.
  • 13. • { name: 'Tom', grade: [ 82, 75, 70 ] } { name: 'Sarah', grade: [ 83, 88, 91 ] } { name: 'Vu', grade: [ 85, 79, 84 ] }
  • 14.
  • 15. Inheritance with the Prototype Chain • When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property (referred to as [[Prototype]] ) which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.
  • 16. • Nearly all objects in JavaScript are instances of Object constructor which sits on the top of a prototype chain. And the prototype of Object’s prototype is not pointing anywhere but just null .
  • 17. The instanceof operator in JavaScript • The instanceof operator tests presence of constructor.prototype in object's prototype chain.
  • 18. References 1. David Herman, Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript (Effective Software Development Series), Addison-Wesley Professional, 1 edition (December 6, 2012). 2. https://stackoverflow.com/questions/6750880/ how-does-the-new-operator-work-in-javascript 3. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference

Editor's Notes

  1. C:\Users\Hong\WebstormProjects\studentgradeproj Question: what’s the result?
  2. Question: what’s the result?
  3. Later, we will see what the value of this is in our example.
  4. So in our example, the value of this is Tom when executing var Tom = new Student("Tom"); Any questions? See Example 2 returnobject.js // defining constructors function C() { this.name = "Jack"; //return {a:1}; }; function D() { this.name = "Linda"; } var o = new C(); var o2 = new D(); console.log(o, o2); //C { name: 'Jack' } D { name: 'Linda' }
  5. Question: Why use prototypes? Using prototypes can save memory. Any questions?
  6. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain Mention example.
  7. See Example 3 instanceof.js in webstorm. // defining constructors function C() {} function D() {} var o = new C(); // true, because: Object.getPrototypeOf(o) === C.prototype console.log(o instanceof C); // false, because D.prototype is nowhere in o's prototype chain console.log(o instanceof D); console.log(o instanceof Object); // true, because: console.log(C.prototype instanceof Object) // true