Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.

Slides:



Advertisements
Similar presentations
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
Advertisements

AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Start Your Own Blog Angel Georgiev Part-time Trainer angeru.softuni-friends.org Software University The Culture of Knowledge Sharing.
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
CSS Transitions and Animations Animated HTML Elements SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Functions and Function Expressions Closures, Function Scope, Nested Functions, IIFE Software University Technical Trainers SoftUni Team.
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Classes, Properties, Constructors, Objects, Namespaces
Extending functionality using Collections
Introduction to TypeScript & Angular
Inheritance and Prototypes
Presentation transcript:

Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team

Table of Contents  The Prototype Chain  Inheritance in Classical OOP  Calling Parent Methods  Prototypal Inheritance 2

The Prototype Chain The Way to Search Properties in JavaScript

 All JavaScript objects inherit methods / properties from their prototype  Properties:  Object.prototype.constructor  Specifies the function that creates an object's prototype  Object.prototype.__proto__  Points to the object which was used as prototype (on instantiation)  Object.prototype.toString  Object.prototype in MDN Object.prototype in MDN Object.prototype

 Objects in JavaScript can have only a single prototype  Their prototype also has a prototype, etc…  This is called the prototype chain  When a property is called on an object 1. This object is searched for the property 2. If the object does not contain such property, its prototype is checked for the property, etc… 3. If a null prototype is reached, the result is undefined The Prototype Chain 5

6 Prototype Chain Object.prototype keyvalue constructorObject toStringfunction() { … } valueOffunction() { … } hasOwnPropertyfunction() { … } isPrototypeOffunction() { … } [[Prototype]]null Person.prototype keyvalue constructorPerson toStringfirstName + lastName firstName lastName [[Prototype]]Object.prototype Student.prototype keyvalue constructorStudent toStringfirstName + lastName + grade grade [[Prototype]]Person.prototype null function Person(fname, lname) { … } function Student(grade) { … } Student.extends(Person); var st = new Student( "Peter", "Petrov", 4); "Peter", "Petrov", 4); st.sayHello();

7  The Object.getPrototypeOf() method returns the prototype of specified object  The value of the internal [[Prototype]] property  Don't use __proto__  It is deprecated getPrototypeOf() function Person(fname, lname) {} var pesho = new Person('Pesho', 'Peshev'); Object.getPrototypeOf(Person); // [Function: Empty] Object.getPrototypeOf(pesho); // Person.prototype

8  The hasOwnProperty() method returns a boolean indicating whether the object has the specified property.  Every object inherits the hasOwnProperty method  Does not traverse the prototype chain  Use hasOwnProperty() instead of traversing the properties hasOwnProperty() var obj = {}; obj.name = 'My Object'; obj.hasOwnProperty('name'); // returns true obj.hasOwnProperty('age'); // returns false obj.hasOwnProperty('toString'); // returns false

Inheritance in Classical OOP Like in C#, Java or C++

 Inheritance is a way to extend the functionality of an object  Like Student inherits Person  In JavaScript inheritance is achieved by setting the prototype of the derived type to an instance of the super type  Now Student objects are also of type Person Inheritance in Classical OOP function Person(fname, lname) {} function Student(fname, lname, grade) {} Student.prototype = new Person(); var student = new Student("Kiro", "Troikata", 7); 10

Student.prototype = Person.prototype;  Doesn't work! Both refer to same object  Adding something to Child.prototype, will be added to Parent.prototype Student.prototype = new Person();  This invokes the constructor which might have undesired side effects Student.prototype = Object.create(Person.prototype);  Set prototype to the new object, created from Person's prototype  Set back the constructor of prototype pointing to Student constructor How to Inherit the prototype Object? 11 Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student;

12  We can add extension method to Object  Which gets parent as parameter  Which sets the prototype of the child to the prototype of the parent  Which return reference of the child prototype to the child constructor Adding extends() method Object.prototype.extends = function (parent) { this.prototype = Object.create(parent.prototype); this.prototype = Object.create(parent.prototype); this.prototype.constructor = this; this.prototype.constructor = this;}

13  Modern browsers already have Object.create(…)  Easy to be fixed for all browsers: Fixing Missing Object.create(…) if (!Object.create) { Object.create = function (proto) { Object.create = function (proto) { function F() {}; function F() {}; F.prototype = proto; F.prototype = proto; return new F(); return new F(); }; };};

Inheritance in Classical OOP Live Demo

15 Person [[Function]] prototypePerson.prototype name"Person" length1 Inheritance in Classical OOP - Diagram Person.prototype [[Object]] constructorPerson() [[Prototype]]Object.prototype Student [[Function]] prototypeStudent.prototype name"Student" length2 Student.prototype [[Object]] constructorStudent() [[Prototype]]Person.prototype pesho firstNamePeter [[Prototype]]Student.prototype Object [[Function]] prototypeObject.prototype Object.prototype [[Object]] constructorObject() [[Prototype]]null

Calling Parent Methods Reusing Logic from the Inherited Class

 JavaScript has no direct way of calling its parent methods  Function constructors actually do not specifywho or what their parent is  Calling parent methods is done using call(…) and apply(…) Calling Parent Methods 17

18 Calling Parent Methods: Example var Shape = (function () { function Shape(x, y) { function Shape(x, y) { // Initialize the shape // Initialize the shape } Shape.prototype = { Shape.prototype = { serialize: function () { serialize: function () { // Serialize the shape // Return the serialized shape // Serialize the shape // Return the serialized shape } }; }; return Shape; return Shape;}()); Define a Shape class

19 Calling Parent Methods: Example (2) var Rect = (function () { function Rect(x, y, width, height) { function Rect(x, y, width, height) { Shape.call(this, x, y); Shape.call(this, x, y); this.witdh = width; this.witdh = width; this.height = height; this.height = height; } Rect.prototype = Object.create(Shape.prototype); Rect.prototype = Object.create(Shape.prototype); Rect.prototype.serialize = function (){ Rect.prototype.serialize = function (){ Shape.prototype.serialize.call(this); Shape.prototype.serialize.call(this); // add Rect-specific serialization // add Rect-specific serialization // and return the serialized rectangle // and return the serialized rectangle }; }; return Rect; return Rect;}()); Calling the parent constructor Calling the parent serialize() function Rect inherits Shape

Calling Parent Methods Live Demo

Prototypal Inheritance Another Way to Work with Classes in JS

 Prototypal inheritance is not like the classical inheritance  All instances are created from a common JS object  instanceof does not work Prototypal Inheritance var person = { init: function(name, age) { init: function(name, age) { this._name = name; this._name = name; this._age = age; this._age = age; }, }, introduce: function() { introduce: function() { return this.name + " " + this.age; return this.name + " " + this.age; }} var student = Object.create(person); student.init('Pesho', 19);

Prototypal Inheritance (2) var person = { init: function init(name, age) { init: function init(name, age) { this.name = name; this.name = name; this.age = age; this.age = age; return this; return this; }, }, introduce: function introduce() { introduce: function introduce() { return this.name + " " + this.age; return this.name + " " + this.age; }}; var student = Object.create(person); student.init = function init(name, age, grade) { person.init.call(this, name, age); person.init.call(this, name, age); this.grade = grade; this.grade = grade; return this; return this;} 23 Call person 's init() method

24  Extend the Person object and add Student specific functionality Prototypal Inheritance – Extend a method var person = { init: function(name) { this.name = name; } } var student = person.extend({ init: function init(name, grade) { init: function init(name, grade) { this._super.init.call(this, name); this._super.init.call(this, name); this.grade = grade; this.grade = grade; return this; return this; }}); Object.prototype.extend = function(properties) { function f() {}; function f() {}; f.prototype = Object.create(this); f.prototype = Object.create(this); for (var prop in properties) { for (var prop in properties) { f.prototype[prop] = properties[prop]; f.prototype[prop] = properties[prop]; } f.prototype._super = this; f.prototype._super = this; return new f(); return new f();} Set the prototype to this of the extended object Add the derived object properties Keep a reference to the super object

Prototypal Inheritance Live Demo

26 personInit [[Function]] prototype… name"Person" length1 Inheritance in Prototypal OOP – Diagram person [[Object]] initpersonInit() [[Prototype]]Object.prototype studentInit [[Function]] prototype… name"studentInit" length2 student [[Object]] initstudentInit() [[Prototype]]Object.prototype pesho firstNamePeter __proto__Student.prototype Object [[Function]] prototypeObject.prototype Object.prototype [[Object]] constructorObject() [[Prototype]]null

27  Constructor Pattern  Functional features can't be used in conjunction with the new keyword  Forgetting to use new leads to unexpected bugs and global variables  Most programmers (from object-oriented language backgrounds) will understand your code  Prototypal Pattern  Functional features can be used in conjunction with create()  Since init() is a function the program will always work as expected  Prototypal inheritance is simple and easy to understand Constructor Pattern vs Prototypal Pattern

? ? ? ? ? ? ? ? ? Prototype Chain and Inheritance

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 29  Attribution: this work may contain portions from  “JavaScript OOP" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript OOPCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg