SlideShare a Scribd company logo
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 ] }
Function-and-prototype defined classes in JavaScript
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 (20)

Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015Small Lambda Talk @Booster2015
Small Lambda Talk @Booster2015
Martin (高馬丁) Skarsaune
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh Dalvi
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
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 Implicit
Martin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
Ravi_Kant_Sahu
 
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
agorolabs
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
Nilesh Dalvi
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
RAKESH P
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
Martin Odersky
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Rangana 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 Scala
Knoldus Inc.
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
Chikugehlot
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael Heron
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
Nilesh Dalvi
 
Scala basic
Scala basicScala basic
Scala basic
Nguyen Tuan
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh 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 Implicit
Martin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin 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 - Exercises
agorolabs
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
Nilesh 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 JavaScript
Rangana 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 Scala
Knoldus Inc.
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
Chikugehlot
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael Heron
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
Nilesh Dalvi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 

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

Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
relay12
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Manikanda kumar
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
Manish Jangir
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
Vernon Kesner
 
Prototype
PrototypePrototype
Prototype
Aditya Gaur
 
The prototype property
The prototype propertyThe prototype property
The prototype property
Hernan Mammana
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
Triphon Statkov
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
Barak Drechsler
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Stoyan Stefanov
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
How prototype works in java script?
How prototype works in java script?How prototype works in java script?
How prototype works in java script?
InnovationM
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
Jussi Pohjolainen
 
JavaScript In Object Oriented Way
JavaScript In Object Oriented WayJavaScript In Object Oriented Way
JavaScript In Object Oriented Way
Borey Lim
 
Java script unleashed
Java script unleashedJava script unleashed
Java script unleashed
Dibyendu Tiwary
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
Javascript
JavascriptJavascript
Javascript
Aditya Gaur
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
relay12
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
Manish Jangir
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
Vernon Kesner
 
The prototype property
The prototype propertyThe prototype property
The prototype property
Hernan Mammana
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
How prototype works in java script?
How prototype works in java script?How prototype works in java script?
How prototype works in java script?
InnovationM
 
JavaScript In Object Oriented Way
JavaScript In Object Oriented WayJavaScript In Object Oriented Way
JavaScript In Object Oriented Way
Borey Lim
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
Ad

Recently uploaded (20)

TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Ad

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 ] }
  • 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

  • #8: C:\Users\Hong\WebstormProjects\studentgradeproj Question: what’s the result?
  • #9: Question: what’s the result?
  • #10: Later, we will see what the value of this is in our example.
  • #13: 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' }
  • #15: Question: Why use prototypes? Using prototypes can save memory. Any questions?
  • #16: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain Mention example.
  • #18: 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