SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
INHERITANCE	
  
About	
  Inheritance	
  
•  Code	
  reuse	
  is	
  important	
  
– Inheritance	
  can	
  help	
  
•  JavaScript	
  does	
  not	
  have	
  classes,	
  so	
  no	
  special	
  
keyword	
  for	
  extending	
  
•  In	
  JS	
  you	
  have	
  lot	
  of	
  ways	
  to	
  do	
  inheritance	
  
– Classical	
  Pa@erns	
  
– Modern	
  Pa@erns	
  or	
  Prototypal	
  Inheritance	
  
Understanding	
  JS	
  Inheritance	
  
•  JS	
  is	
  not	
  class	
  based,	
  it’s	
  prototype-­‐based!	
  
•  Object	
  inherit	
  from	
  another	
  object	
  
•  JS	
  contains	
  syntax	
  and	
  features	
  that	
  make	
  it	
  
seem	
  class	
  based	
  
	
  
Understanding	
  Prototypes	
  
•  Prototype	
  is	
  an	
  object	
  from	
  which	
  other	
  
objects	
  inherit	
  properGes	
  
•  Any	
  object	
  can	
  be	
  a	
  prototype	
  
•  Every	
  object	
  has	
  internal	
  __proto__	
  property	
  
Example	
  
var parent = {
method1: function() { print("A"); }
}
var child = {
__proto__: parent,
method2: function() { print("B"); }
}
// If method1 is not found in child, look it from
// prototype!
child.method1(); // A
child.method2(); // B
__proto__	
  
•  __proto__	
  is	
  depricated	
  and	
  should	
  not	
  be	
  
used	
  (but	
  it	
  works)	
  
•  To	
  get	
  the	
  prototype,	
  use	
  
– Object.getPrototypeOf(object)	
  
•  It’s	
  read	
  only!	
  
•  How	
  to	
  set?	
  
– Proposal:	
  Object.setPrototypeOf(obj,	
  prototype)	
  
•  Not	
  possible	
  to	
  change	
  the	
  __proto__	
  ..!	
  
FuncGon	
  Object	
  
•  When	
  wriGng	
  
– function Animal() { }
•  Lot	
  of	
  things	
  happens!	
  
– Two	
  objects	
  created:	
  	
  
•  1)	
  Animal	
  
•  2)	
  Animal.prototype	
  
– Animal.prototype	
  has	
  a	
  property	
  constructor,	
  that	
  
points	
  to	
  Animal	
  
FuncGon	
  Object	
  
// This is just a function. Dog is Function object!
function Dog (name) {
this.name = (name);
}
var spot = new Dog("Spot");
// true
print(spot instanceof Object);
// true
print(Dog instanceof Function);
// true
print(Dog instanceof Object);
FuncGon	
  Object	
  
function sum1(a, b) {
return a + b;
}
// =>
var sum2 = new Function("a","b", "return a+b;");
print(sum1(2,2)); // 4
print(sum2(2,2)); // 4
print(sum2.length); // number of args = 2
print(sum2.toString());
The	
  “new”	
  Operator	
  
function Person() {
this.name = “Jack”;
}
// Normal function call
Person();
// Object creation
var p = new Person();
Example	
  
function Cat() { }
// c.__proto__ points to Cat.prototype!
var c = new Cat();
// true
print(c.__proto__ === Cat.prototype);
// c inherites Cat.prototype!
Cat.prototype.age = 12;
// 12!
print(c.age);
Example	
  
function Cat() { this.name = "Jack"; }
var c = new Cat();
// true
print(c.__proto__ === Cat.prototype);
// c inherites Cat.prototype! Let's add stuff.
Cat.prototype.age = 12;
Cat.prototype.saySomething = function() {
print(this.name + ": hello!");
}
// 12!
print(c.age);
// "Jack: hello!"
c.saySomething();
/** PERSON **/
function Person() { }
var jack = new Person();
// jack inherites Person.prototype!
print(jack.__proto__ === Person.prototype);
Person.prototype.age = 18;
print(jack.age); // 18;
//** STUDENT **/
function Student() { }
// Let's now change the prototype of Student.
// Now Student.prototype points to Person.
var temp = new Person();
Student.prototype = temp;
var tina = new Student();
// tina inherites Student.prototype.. which is now temp!
print(tina.__proto__ === Student.prototype); // true
print(tina.__proto__ === temp); // true
// Now tina inherites Student.prototype, which is
// Person object, which inherites the Person.prototype..
print(tina.age); // 18!
Example	
  
/** Person **/
function Person() {
this.name = "Jack";
}
// Adding functionality to the prototype..
Person.prototype.say = function() {
print(this.name + ”: hello!");
}
/** Student **/
function Student() { }
// Inheritance
Student.prototype = new Person();
/** Test **/
var student = new Student();
student.say(); // Jack: Hello
Person.prototype	
  
say()	
  
new	
  Person()	
  
name	
  =	
  “Jack”	
  
__proto__	
  
Example	
  
/** Person **/
function Person() {
this.name = "Jack";
}
// Adding functionality to the prototype.. What is this??
Person.prototype.say = function() {
print(this.name + ”: hello!");
}
/** Student **/
function Student() { }
// Inheritance
Student.prototype = new Person();
/** Test **/
var student = new Student();
student.say(); // Jack: Hello
Person.prototype	
  
say()	
  
new	
  Person()	
  
name	
  =	
  “Jack”	
  
__proto__	
  
new	
  Student()	
  
__proto__	
  
FuncGon	
  Object	
  
•  Every	
  funcGon	
  in	
  JS	
  is	
  a	
  FuncGon	
  object	
  
•  When	
  	
  
– var spot = new Dog(“spot”);
•  Then	
  spot’s	
  __proto__	
  points	
  to	
  
Dog.prototype!	
  
•  If	
  a	
  property	
  cannot	
  be	
  found	
  in	
  an	
  object,	
  it	
  
is	
  searched	
  for	
  in	
  that	
  object's	
  prototype.	
  
Example	
  
// here's the constructor:
function Point() { }
var a = new Point();
print (a.x); // undefined
// set up the prototype object to have some values:
Point.prototype = { x: 10, y: 20 };
// or you could do this:
Point.prototype.z = 30;
// make a new Point object
// (a object gets an implicit reference to Point.prototype object)
var a = new Point();
// Since a does not hold a property, let's look it from Point.prototype
print (a.x);
Example	
  
// here's the constructor:
function Point() {
this.x = 10;
this.y = 20;
}
// set up the prototype object to have some values:
Point.prototype.z = 40;
// make a new Point object
// (a object gets an implicit reference to Point.prototype object)
var a = new Point();
// Since a does not hold a property, let's look it from Point.prototype
print (a.z);
//** POINT **
function Point() {
}
// set up the prototype object to have some values:
Point.prototype = { x: 10, y: 20 };
/** PIXEL **/
function Pixel() {
}
Pixel.prototype = new Point();
Pixel.prototype.color = "red";
// make a new Point object
// (a object gets an implicit reference to Point.prototype object)
var a = new Pixel();
var b = new Pixel();
a.color = "blue";
// Since a does not hold a property, let's look it from Point.prototype
print (a.color);
print (b.color);
About	
  constructors	
  
•  Prototype	
  properGes	
  of	
  FuncGons	
  have	
  a	
  
constructor	
  property:	
  
– var	
  dog	
  =	
  new	
  Dog();	
  
– dog.constructor	
  ==	
  Dog;	
  //	
  TRUE	
  
•  This	
  will	
  break	
  when	
  doing	
  inheritance!	
  
/** Person **/
function Person() {
}
Person.prototype.name = "Jack";
/** Student **/
function Student() {
this.id = "12345";
}
// Inheritance
Student.prototype = new Person();
Student.prototype.id = "12345";
/** Test **/
var student = new Student();
student.age = 22;
print(student.age)
print(student.name);
print(student.id);
var person = new Person();
print(person.constructor === Person); // TRUE
var student = new Student();
print(student.constructor === Student); // FALSE
/** Person **/
function Person() {
}
Person.prototype.name = "Jack";
/** Student **/
function Student() {
this.id = "12345";
}
// Inheritance
Student.prototype = new Person();
Student.prototype.id = "12345";
// FIX
Student.prototype.constructor = Student;
/** Test **/
var student = new Student();
student.age = 22;
print(student.age)
print(student.name);
print(student.id);
var person = new Person();
print(person.constructor === Person); // TRUE
var student = new Student();
print(student.constructor === Student); // FALSE
Inheritance:	
  Prototypal	
  
•  In	
  EcmaScript	
  5	
  a	
  protypal	
  inheritance	
  pa@ern	
  is	
  
part	
  of	
  the	
  language	
  
–  Object.create()	
  
–  var	
  child	
  =	
  Object.create(parent);	
  
•  The	
  create-­‐funcGon	
  
function create(o) {
function F() {}
f.prototype = o;
return new F();
}
Example	
  
function Point(x,y) {
this.x = x;
this.y = y;
}
var pixel = Object.create(new Point(12,0));
pixel.color = "red";
print(pixel.x);
print(pixel.color);

Mais conteúdo relacionado

Mais procurados

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 

Mais procurados (20)

Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Magic methods
Magic methodsMagic methods
Magic methods
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 

Destaque (9)

New ES6 Hotness
New ES6 HotnessNew ES6 Hotness
New ES6 Hotness
 
JavaScript Inheritence
JavaScript  InheritenceJavaScript  Inheritence
JavaScript Inheritence
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Javascript foundations: Inheritance
Javascript foundations: InheritanceJavascript foundations: Inheritance
Javascript foundations: Inheritance
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
JavaScript: The prototype Property
JavaScript: The prototype PropertyJavaScript: The prototype Property
JavaScript: The prototype Property
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
 
Prototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScriptPrototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScript
 

Semelhante a JavaScript Inheritance

Java script object model
Java script object modelJava script object model
Java script object model
James Hsieh
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 

Semelhante a JavaScript Inheritance (20)

Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Java script object model
Java script object modelJava script object model
Java script object model
 
Prototype
PrototypePrototype
Prototype
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented Programming
 
JavaScript In Object Oriented Way
JavaScript In Object Oriented WayJavaScript In Object Oriented Way
JavaScript In Object Oriented Way
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
 
4front en
4front en4front en
4front en
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 

Mais de Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
Jussi Pohjolainen
 

Mais de Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

JavaScript Inheritance

  • 2. About  Inheritance   •  Code  reuse  is  important   – Inheritance  can  help   •  JavaScript  does  not  have  classes,  so  no  special   keyword  for  extending   •  In  JS  you  have  lot  of  ways  to  do  inheritance   – Classical  Pa@erns   – Modern  Pa@erns  or  Prototypal  Inheritance  
  • 3. Understanding  JS  Inheritance   •  JS  is  not  class  based,  it’s  prototype-­‐based!   •  Object  inherit  from  another  object   •  JS  contains  syntax  and  features  that  make  it   seem  class  based    
  • 4. Understanding  Prototypes   •  Prototype  is  an  object  from  which  other   objects  inherit  properGes   •  Any  object  can  be  a  prototype   •  Every  object  has  internal  __proto__  property  
  • 5. Example   var parent = { method1: function() { print("A"); } } var child = { __proto__: parent, method2: function() { print("B"); } } // If method1 is not found in child, look it from // prototype! child.method1(); // A child.method2(); // B
  • 6. __proto__   •  __proto__  is  depricated  and  should  not  be   used  (but  it  works)   •  To  get  the  prototype,  use   – Object.getPrototypeOf(object)   •  It’s  read  only!   •  How  to  set?   – Proposal:  Object.setPrototypeOf(obj,  prototype)   •  Not  possible  to  change  the  __proto__  ..!  
  • 7. FuncGon  Object   •  When  wriGng   – function Animal() { } •  Lot  of  things  happens!   – Two  objects  created:     •  1)  Animal   •  2)  Animal.prototype   – Animal.prototype  has  a  property  constructor,  that   points  to  Animal  
  • 8. FuncGon  Object   // This is just a function. Dog is Function object! function Dog (name) { this.name = (name); } var spot = new Dog("Spot"); // true print(spot instanceof Object); // true print(Dog instanceof Function); // true print(Dog instanceof Object);
  • 9. FuncGon  Object   function sum1(a, b) { return a + b; } // => var sum2 = new Function("a","b", "return a+b;"); print(sum1(2,2)); // 4 print(sum2(2,2)); // 4 print(sum2.length); // number of args = 2 print(sum2.toString());
  • 10. The  “new”  Operator   function Person() { this.name = “Jack”; } // Normal function call Person(); // Object creation var p = new Person();
  • 11.
  • 12. Example   function Cat() { } // c.__proto__ points to Cat.prototype! var c = new Cat(); // true print(c.__proto__ === Cat.prototype); // c inherites Cat.prototype! Cat.prototype.age = 12; // 12! print(c.age);
  • 13. Example   function Cat() { this.name = "Jack"; } var c = new Cat(); // true print(c.__proto__ === Cat.prototype); // c inherites Cat.prototype! Let's add stuff. Cat.prototype.age = 12; Cat.prototype.saySomething = function() { print(this.name + ": hello!"); } // 12! print(c.age); // "Jack: hello!" c.saySomething();
  • 14. /** PERSON **/ function Person() { } var jack = new Person(); // jack inherites Person.prototype! print(jack.__proto__ === Person.prototype); Person.prototype.age = 18; print(jack.age); // 18; //** STUDENT **/ function Student() { } // Let's now change the prototype of Student. // Now Student.prototype points to Person. var temp = new Person(); Student.prototype = temp; var tina = new Student(); // tina inherites Student.prototype.. which is now temp! print(tina.__proto__ === Student.prototype); // true print(tina.__proto__ === temp); // true // Now tina inherites Student.prototype, which is // Person object, which inherites the Person.prototype.. print(tina.age); // 18!
  • 15. Example   /** Person **/ function Person() { this.name = "Jack"; } // Adding functionality to the prototype.. Person.prototype.say = function() { print(this.name + ”: hello!"); } /** Student **/ function Student() { } // Inheritance Student.prototype = new Person(); /** Test **/ var student = new Student(); student.say(); // Jack: Hello Person.prototype   say()   new  Person()   name  =  “Jack”   __proto__  
  • 16. Example   /** Person **/ function Person() { this.name = "Jack"; } // Adding functionality to the prototype.. What is this?? Person.prototype.say = function() { print(this.name + ”: hello!"); } /** Student **/ function Student() { } // Inheritance Student.prototype = new Person(); /** Test **/ var student = new Student(); student.say(); // Jack: Hello Person.prototype   say()   new  Person()   name  =  “Jack”   __proto__   new  Student()   __proto__  
  • 17. FuncGon  Object   •  Every  funcGon  in  JS  is  a  FuncGon  object   •  When     – var spot = new Dog(“spot”); •  Then  spot’s  __proto__  points  to   Dog.prototype!   •  If  a  property  cannot  be  found  in  an  object,  it   is  searched  for  in  that  object's  prototype.  
  • 18. Example   // here's the constructor: function Point() { } var a = new Point(); print (a.x); // undefined // set up the prototype object to have some values: Point.prototype = { x: 10, y: 20 }; // or you could do this: Point.prototype.z = 30; // make a new Point object // (a object gets an implicit reference to Point.prototype object) var a = new Point(); // Since a does not hold a property, let's look it from Point.prototype print (a.x);
  • 19. Example   // here's the constructor: function Point() { this.x = 10; this.y = 20; } // set up the prototype object to have some values: Point.prototype.z = 40; // make a new Point object // (a object gets an implicit reference to Point.prototype object) var a = new Point(); // Since a does not hold a property, let's look it from Point.prototype print (a.z);
  • 20. //** POINT ** function Point() { } // set up the prototype object to have some values: Point.prototype = { x: 10, y: 20 }; /** PIXEL **/ function Pixel() { } Pixel.prototype = new Point(); Pixel.prototype.color = "red"; // make a new Point object // (a object gets an implicit reference to Point.prototype object) var a = new Pixel(); var b = new Pixel(); a.color = "blue"; // Since a does not hold a property, let's look it from Point.prototype print (a.color); print (b.color);
  • 21. About  constructors   •  Prototype  properGes  of  FuncGons  have  a   constructor  property:   – var  dog  =  new  Dog();   – dog.constructor  ==  Dog;  //  TRUE   •  This  will  break  when  doing  inheritance!  
  • 22. /** Person **/ function Person() { } Person.prototype.name = "Jack"; /** Student **/ function Student() { this.id = "12345"; } // Inheritance Student.prototype = new Person(); Student.prototype.id = "12345"; /** Test **/ var student = new Student(); student.age = 22; print(student.age) print(student.name); print(student.id); var person = new Person(); print(person.constructor === Person); // TRUE var student = new Student(); print(student.constructor === Student); // FALSE
  • 23. /** Person **/ function Person() { } Person.prototype.name = "Jack"; /** Student **/ function Student() { this.id = "12345"; } // Inheritance Student.prototype = new Person(); Student.prototype.id = "12345"; // FIX Student.prototype.constructor = Student; /** Test **/ var student = new Student(); student.age = 22; print(student.age) print(student.name); print(student.id); var person = new Person(); print(person.constructor === Person); // TRUE var student = new Student(); print(student.constructor === Student); // FALSE
  • 24. Inheritance:  Prototypal   •  In  EcmaScript  5  a  protypal  inheritance  pa@ern  is   part  of  the  language   –  Object.create()   –  var  child  =  Object.create(parent);   •  The  create-­‐funcGon   function create(o) { function F() {} f.prototype = o; return new F(); }
  • 25. Example   function Point(x,y) { this.x = x; this.y = y; } var pixel = Object.create(new Point(12,0)); pixel.color = "red"; print(pixel.x); print(pixel.color);