Computer Science

Javascript Object Prototypes

Javascript Object Prototypes are a fundamental concept in Javascript programming. They allow objects to inherit properties and methods from other objects, creating a hierarchy of objects. This enables developers to write more efficient and reusable code.

Written by Perlego with AI-assistance

8 Key excerpts on "Javascript Object Prototypes"

  • Secrets of the JavaScript Ninja, Second Edition
    You’ve learned that functions are first-class objects in JavaScript, that closures make them incredibly versatile and useful, and that you can combine generator functions with promises to tackle the problem of asynchronous code. Now we’re ready to tackle another important aspect of JavaScript: object prototypes.
    A prototype is an object to which the search for a particular property can be delegated to. Prototypes are a convenient means of defining properties and functionality that will be automatically accessible to other objects. Prototypes serve a similar purpose to that of classes in classical object-oriented languages. Indeed, the main use of prototypes in JavaScript is in producing code written in an object-oriented way, similar to, but not exactly like, code in more conventional, class-based languages such as Java or C#.
    In this chapter, we’ll delve into how prototypes work, study their connection with constructor functions, and see how to mimic some of the object-oriented features often used in other, more conventional object-oriented languages. We’ll also explore a new addition to JavaScript, the class keyword, which doesn’t exactly bring full-featured classes to JavaScript but does enable us to easily mimic classes and inheritance. Let’s start exploring.

    Do you know?

    Q1:
    How do you test whether an object has access to a particular property?
    Q2:
    Why is a prototype chain important for working with objects in JavaScript?
    Q3:
    Do ES6 classes change how JavaScript works with objects?

    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:
  • JavaScript
    eBook - ePub

    JavaScript

    Syntax and Practices

    valueOf() method is used to convert an object to another primitive data type instead of a string. Many built-in classes provide their own implementation for the method. Whenever primitive data values are required from an object instead of String, this method can be implemented by the class.

    3.6 Prototypal Inheritance

    Programming languages like PHP, Java and Python are class-based languages and use classes for object creation. JavaScript is a class-based as well as a prototype-based language, which offers prototypes and later supported classes to create objects. Using prototypes, different properties can be shared through generalized objects that can be further cloned, extended or inherited [72] . Extending functionality using prototypes is called as prototypal inheritance. Every object in JavaScript inherits from prototypes either directly or indirectly.
    Apart from having its own set of properties, every object in JavaScript inherits its properties from another object. Generic objects from which the properties and methods are inherited are referred to as the prototype. For instance, all objects inherit from the same prototype object, i.e. Object.prototype. All the created objects in JavaScript have Object as its prototype. It is the final parent for all objects, and accessing anything beyond it will result in null.
    As depicted in Figure 3.2 , every other prototype inherits from Object.prototype. Any type of array, function, regular expression, Number, String or user-created object inherits from Object.prototype. This allows calling the properties and methods defined in Object prototype by all the other objects. Using prototypes thus helps in adding more functionality to objects without the need of declaring them with every class or object.
    Figure 3.2
    Hierarchy of inheritance via Object.prototype.
    Every object also has a hidden internal property called __proto__, which is inaccessible directly in code. This hidden property can be accessed by using the provided static method of Object prototype, i.e. Object.getPrototypeOf(obj)
  • JavaScript for Gurus
    eBook - ePub

    JavaScript for Gurus

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

    Prototypes in JavaScript enable us to make our code a bit more Object Oriented. JavaScript prototypes help us construct objects nicely. Yes, classes do the same thing, but prototypes address several shortcomings of ordinary JavaScript classes.
    There are different prototypes, and we will investigate a few of them. The fun part of this chapter starts with inheritance and Mixins where we can borrow properties and methods from other JavaScript classes

    Structure

    • What are prototypes?
    • Prototypal inheritance
    • Mixins

    Objectives

    • Learn the different types of prototypes
    • Understand the need for prototypes
    • Understand prototypal inheritance
    • Understand Mixins

    What are prototypes?

    Prototypes in JavaScript enable us to make our code a bit more object-oriented. JavaScript prototypes help us construct objects nicely. Yes, classes do the same thing, but prototypes address several shortcomings of ordinary JavaScript classes.
    There are two prototypes in JavaScript, namely prototype and [[Prototype]]:
    • prototype : The prototype is assigned as a property of any function you create in JavaScript, as explained in Chapter 6: JavaScript Classes .
    • [[Prototype]] : Each object that is accessed by the running context has a [[Prototype]] property, which gets read when a certain property on the object being read, is not available.
    OK, this doesn’t really make sense now, does it? No. Let’s have a closer look.
    We have learned in Chapter 6: JavaScript Classes , that you can create objects by using a constructor function. Let’s have a look at the below example:
    function Student(studentFirstName, studentLastName) { this.studentFirstName = studentFirstName, this.studentLastName = studentLastName, this.studentFullName = function() { return this.studentFirstName + “ “ + this.studentLastName; } } var student1 = new Student(“Ockert”, “du Preez”); var student2 = new Student(“BpB”, “Publications”); console.log(student1) console.log(student2)
    The function Student is the constructor function for a Student object. It includes the first name and last name parameters, or in this case, properties. studentFullName
  • Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    sayName() function. To understand how this works, you must understand the nature of prototypes in ECMAScript.
    How Prototypes Work
    Whenever a function is created, its prototype property is also created according to a specific set of rules. By default, all prototypes automatically get a property called constructor that points back to the function on which it is a property. In the previous example, for instance, Person.prototype.constructor points to Person . Then, depending on the constructor, other properties and methods may be added to the prototype.
    When defining a custom constructor, the prototype gets the constructor property only by default; all other methods are inherited from Object . Each time the constructor is called to create a new instance, that instance has an internal pointer to the constructor's prototype. In ECMA-262, this is called [[Prototype]] . There is no standard way to access [[Prototype]] from script, but Firefox, Safari, and Chrome all support a property on every object called __proto__
  • JavaScript: Novice to Ninja
    • Darren Jones(Author)
    • 2017(Publication Date)
    • SitePoint
      (Publisher)

    Chapter 12: Object-Oriented Programming in JavaScript

    Object-oriented programming (OOP for short) is a style of programming that involves separating the code into objects that have properties and methods. This approach has the benefit of keeping related pieces of code encapsulated in objects that maintain state throughout the life of the program. The objects can also be reused or easily modified, as required. JavaScript obviously supports objects, as we saw in Chapter 5 , so it also supports an object-oriented style of programming. In this chapter, we’ll look at what object-oriented programming is and how to implement it in JavaScript.
    In this chapter, we’ll cover the following topics:
    • An introduction to OOP
    • Constructor functions
    • Using classes in JavaScript
    • Prototypes
    • Public and private methods
    • Inheritance
    • Creating objects from objects
    • Adding methods to built-in objects
    • Mixins
    • Chaining functions
    • This and that
    • Borrowing methods from prototypes
    • Our project ― create questions in an OOP way

    Object-Oriented Programming

    Object-oriented programming is often used to model representations of objects in the real world. There are three main concepts in OOP: encapsulation, polymorphism and inheritance. I’m going to use my juicer to illustrate how each of these concepts can be applied in a programming environment, since the juicer can be considered an object. It’s a wonderful machine that makes fresh juice for me every morning. In many ways, my juicer can be thought of as an object, as it has properties such as speed and capacity, and also has methods or actions it can perform, such as juicing, switching on and switching off.

    Encapsulation

    When I use my juicer, I put the fruit into the machine, press the 'on' button and out comes the juice. I haven’t a clue how it does it—only that it makes a very loud noise! This demonstrates the concept of encapsulation: the inner workings are kept hidden inside the object and only the essential functionalities are exposed to the end user, such as the 'on' button. In OOP, this involves keeping all the programming logic inside an object and making methods available to implement the functionality, without the outside world needing to know how
  • Prototype and Scriptaculous in Action
    Prototype’s coding style makes considerable use of JSON. There is also a lot of coverage of JSON within the Ajax press as a lightweight, friendlier alternative to XML for encoding Ajax responses. We already encountered JSON briefly in this capacity in chapter 3. JSON is easy to write and satisfyingly simple, but it is still limited to creating unique instances of objects. In the next section, we’ll see how to define reusable object types. 8.2.2. Defining object types using prototypes The ways in which we’ve created objects so far has been suitable for defining one-off objects, but often we will want to define a type of object with standard properties and behavior that we can then create several instances of. In our image gallery application, for example, we’ll want to create tens, if not hundreds, of objects to represent pictures. In an object-oriented language, we would accomplish this by defining a class definition, but, as we noted, we have no class definitions in JavaScript. We do, however, have access to object prototypes. A prototype is a collection of properties and methods that can be automatically attached to an object when it is created. To define a custom object type, we simply need to define a function that will serve as a constructor, and attach other properties and methods to the prototype of that function. This may sound complex, but in practice, it is reasonably straightforward. Let’s look at how to define a reusable object type for our picture class. First, we define a constructor function: function Picture(id, title, date, details){ this.id=id; this.title=title; this.date=date; this.details=details; } Our picture object also had a getAge() method, which we would like to make available to the Picture type
  • Mastering JavaScript Object-Oriented Programming
    Of course, the lack of a notion of class in JavaScript affects the inheritance mechanism. In fact, while in classical OOP inheritance is an operation allowed on classes, in prototypal OOP inheritance is an operation on objects.
    That does not mean that classical OOP is better than prototypal OOP or vice versa. They are simply different approaches. However, we cannot ignore that these differences lead to some impact in the way we manage objects. At least we note that while in classical OOP classes are immutable, that is we cannot add, change, or remove properties or methods at runtime, in prototypal OOP objects and prototypes are extremely flexible. Moreover, classical OOP adds an extra level of abstraction with classes, leading to a more verbose code, while prototypal OOP is more immediate and requires a more compact code.
    Passage contains an image

    Summary

    In this chapter, we explored the basic principles of the OOP paradigm. We have been focusing on abstraction to define objects, association, aggregation, and composition to define relationships between objects, encapsulation, inheritance, and polymorphism principles to outline the basic principles required by OOP. We have seen how JavaScript supports all features that allow us to define it as a true OOP language and have compared classical OOP with prototypal OOP.
    Once we established that JavaScript is a true Object-Oriented language like other languages such as Java, C #, and C ++, we will continue in the coming chapters by exploring how to take advantage of OOP support for our applications. In particular, in the next chapter we will focus on encapsulation and information hiding, analyzing the advanced JavaScript support and the most common patterns.
    Passage contains an image

    Chapter 3. Working with Encapsulation and Information Hiding

    In this chapter, we will explore the relationship between encapsulation and information hiding, and we will see the different approaches to implement the visibility and accessibility of members of a JavaScript object. The following topics will be addressed in this chapter:
  • AI for Games, Third Edition
    • Ian Millington(Author)
    • 2019(Publication Date)
    • CRC Press
      (Publisher)
    class keyword, to make it more accessible for programmers of other languages, but classes are still implemented under the hood using prototypes.
    Prototypes differ from classes in that any object can inherit from any other object. In a class-based language objects come in two flavors: classes and instances. Instances can inherit only from classes, and classes have a limited form of inheritance from one another, usually called subclassing. This is much simpler in prototypical languages. There is only inheritance, and any object can inherit from any other object. The practical upshot of this is that we are not limited to the two level hierarchy of class and instance. In Section 5.4 , discussing behavior trees, I described the common need for three levels when defining and instantiating AI. This maps nicely into JavaScript. It has the effect of allowing developers to create one root object for a broad class of characters, then an object can inherit from that to configure the settings for a particular character type (this intermediate stage may be done by a level designer or technical artist), and then a final step can see an object instantiate the character type for an individual character in the level.
    Unlike the other languages in this section, JavaScript is single threaded. As a language for augmenting web pages, it was designed to be event driven: the JavaScript runtime monitors for particular events (such as user input, network activity, or scheduled timeouts); when an event occurs, the runtime calls code that has been registered as interested; this code then runs sequentially for as long as it needs; and when there is no more code to run, control returns to the runtime, which waits until another event occurs. Code is guaranteed not to be interrupted while running, and no other code will be run at the same time. This is perfect for simple scripts in a browser, but some things take much longer to complete. We don’t want the whole JavaScript process to grind to a halt waiting for a result. In a web browser, this might be querying for data across the network, which in some cases might be measured in seconds. JavaScript uses callbacks for this (in later versions of JavaScript, these are wrapped in easier to use structures such as promises or ‘async’, though the underlying behavior is the same). A callback uses the same event process. You register some code to be called when an action completes (when the results from the server is received, for example), then start the action. This allows many callbacks to be waiting for data at any time. It is perfect for many server applications, where the code needs to wait for data from the database, from other services, or for files to be read.
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.