Computer Science

Javascript Classes

Javascript classes are a way to create reusable objects with properties and methods. They provide a blueprint for creating objects and allow for inheritance and polymorphism. Classes can be instantiated to create multiple instances of the same object.

Written by Perlego with AI-assistance

8 Key excerpts on "Javascript Classes"

  • Book cover image for: JavaScript
    eBook - ePub

    JavaScript

    The New Toys

    • T. J. Crowder(Author)
    • 2020(Publication Date)
    • Wrox
      (Publisher)
    But classes are more than just the largely static constructs those sorts of languages provide. In the more general sense, for a language to have classes it has to provide two things: encapsulation (bundling data and methods together 1) and inheritance. Having classes isn't the same as being class-based, it's just that the language supports encapsulation and inheritance. Prototypical languages can (and do) have classes and have since before JavaScript was invented; the mechanism they use to provide the second requirement (inheritance) is prototype objects. JavaScript has always been one of the most object-oriented languages you'll find. It's certainly been able to do things in a class-like way since at least ECMAScript 1. Some might pedantically argue it didn't have classes in a computer science sense until ES5 added Object.create to directly support inheritance (even though you could emulate Object.create with a helper function). Others might argue even ES5 doesn't qualify because it lacks declarative constructs and a simple way to refer to superclass methods. But the pedants can stop arguing. As of ES2015, even those objections are laid to rest: JavaScript has classes. Let's see how they work in modern JavaScript. Along the way, we'll compare the new syntax with the old ES5 and earlier syntax. INTRODUCING THE NEW CLASS SYNTAX Listing 4-1 shows a basic example of class : a class whose instances are colors expressed in RGB. (The listing has some method body code omitted, because the goal here is just to show the overall syntax
  • Book cover image for: 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.
  • Book cover image for: Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    8 Objects, Classes, and Object-Oriented Programming

    WHAT'S IN THIS CHAPTER?

    • Understanding objects
    • Understanding object creation
    • Understanding inheritance
    • Understanding classes
    ECMA-262 defines an object as an unordered collection of properties. Strictly speaking, this means that an object is an array of values in no particular order. Each property or method is identified by a name that is mapped to a value. For this reason (and others yet to be discussed), it helps to think of ECMAScript objects as hash tables: nothing more than a grouping of name-value pairs where the value may be data or a function.

    UNDERSTANDING OBJECTS

    The canonical way of creating a custom object is to create a new instance of Object and add properties and methods to it, as in this example:
    let person = new Object(); person.name = "Nicholas"; person.age = 29; person.job = "Software Engineer"; person.sayName = function() { console.log(this.name); };
    This example creates an object called person that has three properties (name , age , and job ) and one method (sayName() ). The sayName() method displays the value of this.name , which resolves to person.name . Early JavaScript developers used this pattern frequently to create new objects. A few years later, object literals became the preferred pattern for creating such objects. The previous example can be rewritten using object literal notation as follows:
    let person = { name: "Nicholas", age: 29, job: "Software Engineer", sayName() { console.log(this.name); } };
    The person object in this example is equivalent to the person object in the prior example, with all the same properties and methods. These properties are all created with certain characteristics that define their behavior in JavaScript.

    Types of Properties

    ECMA-262 describes characteristics of properties through the use of internal-only attributes. These attributes are defined by the specification for implementation in JavaScript engines, and as such, these attributes are not directly accessible in JavaScript. To indicate that an attribute is internal, surround the attribute name with two pairs of square brackets, such as [[Enumerable]]
  • Book cover image for: Web Programming
    eBook - PDF

    Web Programming

    Building Internet Applications

    • Chris Bates(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    If we were modelling an 200 7. Objects in JavaScript object-oriented human we would start by modelling each of those systems. We would then combine those systems to make more complex pieces, finally we would join all of the pieces together to make a person. NOTE A class is a description of something; an object is an instance of a class. It is the object that exists in the computer’s memory and which does the work. In summary: • an object is described by a class • a class can be specialized through inheritance • a class usually contains both data items and processing capability. JavaScript Objects So does JavaScript implement all of that object stuff? Well it would be true to say that it does and then again it does not. The built-in JavaScript objects such as document and window act, and are used, like standard OO objects. I will be showing how to use these in Section 7.4. Where JavaScript diverges from traditional OO is in its treatment of user-defined objects. An object is really a data structure that has been associated with some functions. It does not have inheritance and the structure of the code can look a little peculiar. The easiest way of understanding how to combine your data and functions into objects is to work through an example. Code first, then explanation: 1
  • Book cover image for: JavaScript for Gurus
    eBook - ePub

    JavaScript for Gurus

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

    ECTION II

    The Power of JavaScript

    Introduction

    Section 2 dives right into the real power of JavaScript. Understanding what makes JavaScript tick is pivotal in creating extremely powerful websites and web applications. In this section, you will learn how to create classes, and then move on to prototypes, properties and promises, finally generators, and modules.
    This section will have the following chapters:
    1. Classes
    2. Prototypes
    3. Properties
    4. Promises
    5. Generators
    6. Modules
    Passage contains an image

    CHAPTER 6

    Javascript Classes

    Introduction

    A JavaScript class creates the structure of its child objects. Although JavaScript is not a full-on object-oriented programming (OOP ) language, it still contains many an OOP feature. Learning how to work with classes is essential to create proper reusable objects.
    In this chapter, we will focus on Javascript Classes. You will learndifferent ways to create classes and how to instantiate child objects from classes. Properties and methods are next. You will learn how to create basic properties and methods to give your classes better structure and better adaptability. Lastly, you will get a quick introduction to inheritance. There is a lot of work, so let’s get started!

    Structure

    • What are classes?
      • Creating a class
      • Class declarations
      • Class expressions
    • Properties
      • Properties of properties
    • Methods
      • Static methods
    • Inheritance

    Objectives

    • Learn what classes are
    • Understand the concepts of properties
    • Understand the concepts of methods
    • Learn what inheritance is

    What are classes?

    A class, in OOP is a template or blueprint from which objects can be created. A class in JavaScript is a type of function which can be created with a class declaration or a class expression.

    Creating a class

    There are essentially two ways to create a class in JavaScript; they are:
    • Declaring a class
    • Using a class expression
    Let’s have a look at examples for each.

    Class declarations

    To declare a class, all you need to do is to use the class keyword and supply name of the class, with a constructor. A constructor is a special type of method where the object can be initialized, and it gets called automatically. You can also supply arguments (parameters) to the class here and initialize them as well. Initialization is the assignment (setting) of an initial value for an object or variable. Here is an example:
  • Book cover image for: 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)
  • Book cover image for: Start Programming Using HTML, CSS, and JavaScript
    For example, arrays, functions, and dates are all native objects. 208 Meeting 11. Building Your Own Objects • Second, user-defined objects are all objects defined by the programmer and cre-ated during the execution of JavaScript code. • The last group are host objects, which are defined by the host environment in which the JavaScript interpreter is running. In our case, host objects will be the browser objects because we run our programs within a browser. 11.3 Classes Professor : The objects complex , conjugate , and englGerm , which we just created, were all unique, each having its own set of properties. It is, however, often useful to define not just properties but also a behavior of an object. For complex numbers, for instance, you could define arithmetic operations. Note that it wouldn’t make much sense to define arithmetic operations for each complex object separately as we did for the im and re property values, which must be unique for each object. In such cases it is more useful to define a class of objects. You may then create members or instances of the defined class, which have their own unique property values that specify their individual state, and methods that define their behavior and are shared by all the members of the class. The following picture shows an imaginary class named Dog and an object instance of this class named myDog . Class Dog Properties: Methods: sitting length sit() bark() quiet() Property values: sitting = false length = 85 name name = Maxwell barking barking = false Object instance myDog come() Methods: sit() bark() quiet() come() Constructor: Dog() You can see how the object instance has the same methods as the class object, while it specifies its own values for the properties. The class also defines a constructor, which is used for instantiating member objects. To a certain extent, you are already familiar with these concepts.
  • Book cover image for: Mastering JavaScript Design Patterns
    monkey patching . There is some division over whether or not this is good practice. It can certainly be useful when dealing with library code but it adds great confusion. It is generally considered to be better practice to extend the existing class.
    Without a proper class system, JavaScript, of course, has no concept of inheritance. What it does have is a prototype. At the most basic level, an object in JavaScript is an associative array of keys and values. Each property or function on an object is simply defined as part of this array.
    You can even see this in action by accessing members of an object using the array syntax, as is shown in the following code: var thing = { a: 7}; console.log(thing["a"]);

    Tip

    Accessing members of an object using the array syntax can be a very handy way to avoid using the eval function. For instance, if I had the name of the function I wanted to call in a string called funcName and I wanted to call it on an object, obj1 , then I could do so by doing obj1[funcName]() instead of using a potentially dangerous call to eval . The eval function allows for arbitrary code to be executed. Allowing this on a page means that an attacker may be able to enter malicious scripts on other people's browsers.
    When an object is created, its definition is inherited from a prototype. Weirdly, each prototype is also an object, so even prototypes have prototypes. Well, except for object, which is the top-level prototype. The advantage to attaching functions to the prototype is that only a single copy of the function is created; saving on memory. There are some complexities to prototypes, but you can certainly survive without knowing about them. To make use of a prototype, you need to assign functions to it, as shown in the following code:
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.