Computer Science

Javascript Inheritance

Javascript Inheritance is a way of creating new objects based on existing objects. It allows objects to inherit properties and methods from other objects, reducing the amount of code needed to create new objects. Inheritance is achieved through the use of prototype chains.

Written by Perlego with AI-assistance

6 Key excerpts on "Javascript Inheritance"

  • Mastering JavaScript Object-Oriented Programming
    superclass . Apart from the naming, the inheritance concept is the same, although of course it does not seem suited to JavaScript.
    We can implement inheritance in JavaScript in various ways. Consider, for example, the following constructor of person objects: function Person() { this.name = ""; this.surname = ""; }
    In order to define a programmer as a person specialized in computer programming, we will add a new property describing its knowledge about a programming language: knownLanguage .
    A simple approach to create the programmer object that inherits properties from person is based on prototype. Here is a possible implementation: function Programmer() { this.knownLanguage = ""; } Programmer.prototype = new Person(); We will create a programmer with the following code: var programmer = new Programmer();
    We will obtain an object that has the properties of the person object (name and surname ) and the specific property of the programmer (knownLanguage ), that is, the programmer object inherits the person properties.
    This is a simple example to demonstrate that JavaScript supports the inheritance principle of Object-Oriented Programming at its basic level. Inheritance is a complex concept that has many facets and several variants in programming, many of them dependent on the used language.
    In Chapter 4 , Inheriting and Creating Mixins , we will explore more in depth how JavaScript supports inheritance, analyzing different approaches and more advanced topics such as overriding and multiple inheritance.

    Polymorphism

    In Object-Oriented Programming, polymorphism is understood in different ways, even if the basis is a common notion—the ability to handle multiple data types uniformly. Support of polymorphism brings benefits in programming that go toward the overall goal of OOP. Mainly, it reduces coupling in our application, and in some cases, allows to create more compact code.
  • Secrets of the JavaScript Ninja, Second Edition

    7.1. Understanding prototypes

    In JavaScript, objects are collections of named properties with values. For example, we can easily create new objects with object-literal notation:
    As we can see, object properties can be simple values (such as numbers or strings), functions, and even other objects. In addition, JavaScript is a highly dynamic language, and the properties assigned to an object can be easily changed by modifying and deleting existing properties:
    We can even add completely new properties: In the end, all these modifications have left our simple object in the following state: { prop1: [], prop3: {}, prop4: "Hello" };
    When developing software, we strive not to reinvent the wheel, so we want to reuse as much code as possible. One form of code reuse that also helps organize our programs is inheritance, extending the features of one object into another. In JavaScript, inheritance is implemented with prototyping.
    The idea of prototyping is simple. Every object can have a reference to its prototype, an object to which the search for a particular property can be delegated to, if the object itself doesn’t have that property. Imagine that you’re in a game quiz with a group of people, and that the game show host asks you a question. If you know the answer, you give it immediately, and if you don’t, you ask the person next to you. It’s as simple as that.
    Let’s take a look at the following listing.
    Listing 7.1. With prototypes, objects can access properties of other objects
    In this example, we start by creating three objects: yoshi, hattori, and kuma. Each has one specific property accessible only to that object: Only yoshi can skulk, only hattori can sneak, and only kuma can creep. See figure 7.1 .
    Figure 7.1. Initially, each object has access to only its own properties.
    To test whether an object has access to a particular property, we can use the in operator. For example, executing skulk in yoshi returns true, because yoshi has access to the skulk property; whereas executing sneak in yoshi returns false.
  • The JavaScript Workshop
    eBook - ePub

    The JavaScript Workshop

    A New, Interactive Approach to Learning JavaScript

    • Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    In this section, we have learned about different types of programming paradigms we can use with JavaScript. We dug deep into two of the most popular paradigms – procedural and object-oriented. We went through different pros and cons of both paradigms. We also learned about two of the most important features of OOP, which are encapsulation and inheritance.

    Basic JavaScript Concepts

    Programming paradigms are important, but to understand them in detail, we need a basic understanding of different JavaScript concepts. So, let's go through some of the core concepts of JavaScript, which will help you get a grasp of JavaScript and give you a better understanding of how we can use programming paradigms to build scalable solutions to problems.

    Prototypes and Prototypical Inheritance

    Objects are very important because they help us manipulate JavaScript to achieve the functionality we want. There are a lot of ways to create objects in JavaScript. One of the ways is by using a constructor function, and whenever we create a function, the JavaScript engine adds a prototype property to the function. This prototype property is an object that has a constructor property by default. This constructor points back to the parent functions. You can see this function by calling functionName.prototype .
    Let's first create a function: function PersonName(first_name, last_name) { this.first_name = first_name; this.last_name = last_name; this.fullName = function(){  return [ this.first_name, this.last_name].join(" ");      }  }
    Now, let's check its prototype property by entering PersonName.prototype .The output will be as follows:
    Figure 13.4: Prototype property of objects
    As you can see, we have created a function named PersonName and JavaScript automatically binds a prototype property to it. You can print the prototype and you can see that there is a constructor property, which holds all the metadata of the parent function.

    What Is Prototypical Inheritance?

    As we know, everything in JavaScript is an object. Every string, integer, array, object, and function that you define is an object of its respective parent class. Each object in JavaScript holds a proto property (__proto__ keys inside child objects are usually referred to as proto properties) that holds all the properties of its parent class. We can use these proto properties to implement inheritance. These prototype objects act as template objects from which all the child objects will inherit methods and properties. We can also override the properties of a parent class using this prototype
  • Web Applications with Javascript or Java
    eBook - ePub

    Web Applications with Javascript or Java

    Volume 2: Associations and Class Hierarchies

    is-instance-of predicate that allows testing if a class is the direct or an indirect type of an object. In addition, it is desirable to be able to inspect inheritance hierarchies with the help of
    1. a predefined instance-level property for retrieving the direct type of an object (or its direct types, if multiple classification is allowed);
    2. a predefined type-level property for retrieving the direct supertype of a type (or its direct supertypes, if multiple inheritance is allowed).
    A special case of an OOP language is JavaScript, which did originally not have an explicit language element for defining classes, but only for defining constructor functions. Due to its dynamic programming features, JavaScript allows using various code patterns for implementing classes, subtyping and inheritance. In modern JavaScript, starting from ES2015, defining a superclass and a subclass is straightforward. First, we define a base class, Person , with two properties, firstName and lastName :
    class Person { constructor (first, last) { // assign base class properties this.firstName = first; this.lastName = last; } }
    Then, we define a subclass, Student , with one additional property, studentNo :
    class Student extends Person { constructor (first, last, studNo) { // invoke constructor of superclass super( first, last); // assign additional properties this.studentNo = studNo; } }
    Notice how the constructor of the superclass is invoked with super( first, last) for assigning the superclass properties.
    12.7.2  Subtyping and Inheritance with XML Schema
    In XML Schema, a subtype can be defined by extending or by restricting an existing complex type. While extending a complex type means extending its intension by adding elements or attributes, restricting a complex type means restricting its extension
  • JavaScript for Gurus
    eBook - ePub

    JavaScript for Gurus

    Use JavaScript programming features, techniques and modules to solve everyday problems

    Now, what if we simply want to take an existing object and extend it? The answer is prototypal inheritance. Inheritance means when you inherit features (methods or properties) from other prototypes. The benefit of inheritance is that after you have inherited the object features, you can extend it, and this saves a lot of work when creating objects and prototypes because you do not have to recreate similar objects.
    Let’s look at an example. The following exercise demonstrates creating a prototype or a class:
    1. Open a text editor of your choice and enter the following HTML and JavaScript code: <html> <body> <h1>prototypal inheritance example</h1> <p>prototypal inheritance example</p> <script> function Student (studentFirstName, studentLastName) { this.studentFirstName = studentFirstName, this.studentLastName = studentLastName } Student.prototype.attendClass = function (timeIn, timeOut) { console.log(this.studentFirstName + ‘ arrived for class at: ‘ + timeIn + ‘ and left at ‘ + timeOut) } Student.prototype.writeExam = function () { console.log(this.studentFirstName + ‘ is writing exam.’) } const student1 = new Student(‘Ockert’, ‘du Preez’); student1.attendClass(‘10:00’, ‘14:00’); student1.writeExam() </script> </body> </html>
    2. Save the file with an HTML extension, for example Chapter 7.4.html .
    3. Double-click the file to open it in the default browser
    4. If the browser is Google Chrome, press Ctrl + Shift + J to open the console window. The Console window will look similar to Figure 7.5 below:
      Figure 7.5: Prototype object
    In the above exercise, you made use of a function to create a Student and included the studentFirstName and studentLastName parameters. You then added two methods to the Student prototype. One method is attendClass and the last method is writeExam . Both functions log a string to the browser’s console window, as shown in Figure 7.5 above.
    Based on the Student prototype we have created, we sit with a problem. If we want to add a programming student, or a web design student, or a literacy student to the project, we’d basically have to duplicate this code for each of the classes or prototypes. So, what now? You will have to inherit from the Student
  • JavaScript: Novice to Ninja
    • Darren Jones(Author)
    • 2017(Publication Date)
    • SitePoint
      (Publisher)
    index.html in your browser. Providing options that the player can choose from makes the game much easier to play by not requiring any typing:
    Multiple-choice options in the quiz
    You can see a live example on CodePen .

    Chapter Summary

    • Object-oriented programming (OOP) is a way of programming that uses objects that encapsulate their own properties and methods.
    • The main concepts of OOP are encapsulation, polymorphism and inheritance.
    • Constructor functions can be used to create instances of objects.
    • ES6 introduced class declarations that use the class keyword. These can be used in place of constructor functions.
    • Inside a constructor function or class declaration, the keyword this refers to the object returned by the function.
    • All instances of a class or constructor function inherit all the properties and methods of its prototype.
    • The prototype is live, so new properties and methods can be added to existing instances.
    • The prototype chain is used to find an available method. If an object lacks a method, JavaScript will check whether its prototype has the method. If not, it will check that function’s prototype until it finds the method or reaches the Object constructor function.
    • Private properties and methods can be created by defining variables using const and defining a function inside a constructor function. These can be made public using getter and setter functions.
    • Monkey-patching is the process of adding methods to built-in objects by augmenting their prototypes. This should be done with caution as it can cause unexpected behavior in the way built-in objects work.
    • A mixin method can be used to add properties and methods from other objects without creating an inheritance chain.
    • Methods can be chained together and called in sequence if they return a reference to this.
    • Polymorphism allows objects to override shared methods with a more specific implementation.
    • The value of this is not retained inside nested functions, which can cause errors. This can be worked around by using that = this , using the bind(this)
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.