One place for hosting & domains

      JavaScript

      Introduction to the Bun JavaScript Runtime


      Bun introduces a new JavaScript runtime with exceptional performance, built-in bundling & transpiling, and first-class support for TypeScript & JSX. This up-and-coming tool promises to be an asset for JavaScript developers and a strong competitor to Node.js and Deno.

      In this tutorial, learn about the Bun JavaScript runtime and how it compares to other runtimes like Node.js and Deno. See how to set up Bun on your own system, and follow along to build an example React application with it.

      Before You Begin

      1. Familiarize yourself with our
        Getting Started with Linode guide, and complete the steps for setting your Linode’s hostname and timezone.

      2. This guide uses sudo wherever possible. Complete the sections of our
        How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        • Debian and Ubuntu:

          sudo apt update && sudo apt upgrade
          
        • AlmaLinux, CentOS Stream (8 or later), Fedora, and Rocky Linux:

          sudo dnf upgrade
          

      Note

      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Users and Groups guide.

      What Is Bun?

      Bun enters the field of JavaScript runtimes opposite options like Node.js and Deno. Built on the lightning-fast JavaScriptCore engine, the Bun runtime stands out for its speed and built-in bundling & transpiling features.

      These next sections aim to make you more familiar with Bun and what it has to offer. Keep reading to learn more about JavaScript runtimes in general, and how Bun stacks up against its main competitors.

      What Are JavaScript Runtimes?

      JavaScript runtimes are tools that allow you to run JavaScript outside of a browser. With a JavaScript runtime, you can use JavaScript to build server, desktop, and mobile applications.

      By far, the predominant JavaScript runtime is Node.js. Built on the V8 JavaScript engine behind Google Chrome, Node.js is the default JavaScript runtime for many developers.

      Recently, the creator of Node.js put out a new JavaScript runtime, Deno. The Deno runtime, like Node.js, is built on the V8 JavaScript engine. However, Deno introduces numerous fundamental improvements to Node.js in terms of security, performance, and more. It also adds first-class support for TypeScript and JSX.

      The Bun Runtime

      The Bun runtime arose with a fresh approach to JavaScript runtimes. Developed using the Zig programming language, Bun constructs its runtime on the JavaScriptCore engine, used in Apple’s Safari web browser. The result is an incredibly fast runtime.

      Additionally, Bun has built-in handling for bundling and transpiling. With other runtimes, you need to rely on outside tools for bundling your JavaScript projects and for transpiling code from another language. Bun handles all of these features.

      What’s more, Bun’s runtime implements the Node.js algorithm for resolving modules. This means that Bun can make use of NPM packages. Bun’s bundler can find and install packages from the vast NPM repository and manage their dependencies, giving you a full-featured and seamless bundler.

      Like Deno, Bun also comes with first-class support for the TypeScript and JSX languages.

      Bun vs Node.js and Deno

      Bun offers some of the same advantages over Node.js as Deno. Besides the aforementioned first-class support for TypeScript and JSX, both offer performance and quality-of-life improvements over Node.js.

      However, the Bun runtime also aims to exceed Deno in terms of performance. Bun’s use of the JavaScriptCore engine has allowed Bun to achieve immense speed gains in its execution of JavaScript programs.

      With Bun, you also get simplified tooling. Bun includes transpiling and bundling features, which keeps you from having to adopt and maintain separate tools for those tasks.

      How to Install Bun

      Before proceeding, make sure your Linux system uses a version supported by Bun. Currently, Bun runs on systems using at least version 5.1 of the Linux kernel (though it prefers 5.6).

      You can check your kernel version with the command:

      uname -r
      

      On a CentOS Stream 9 system, for instance, you could expect an output like the following:

      5.14.0-80.el9.x86_64

      For reference, here are versions of some popular Linux distributions that use at least version 5.1 of the Linux kernel:

      • CentOS Stream (9 or newer)
      • Debian (11 or newer)
      • Fedora (34 or newer)
      • Ubuntu (20.04 LTS or newer)

      The Bun installation script requires that you have Unzip installed on your system. You can install Unzip using one of the following commands:

      • Debian and Ubuntu:

        sudo apt install unzip
        
      • AlmaLinux, CentOS Stream, Fedora, and Rocky Linux:

        sudo dnf install unzip
        

      Bun can be installed using an installation script. The command below accesses the script and runs it in your shell session:

      curl https://bun.sh/install | bash
      

      Once finished, the Bun installation script displays a success message:

      bun was installed successfully to /home/example-user/.bun/bin/bun
      [...]

      The script may also inform you to add two lines to your .bashrc file. You can quickly do so using the following commands:

      echo 'export BUN_INSTALL="/home/example-user/.bun"' >> ~/.bashrc
      echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> ~/.bashrc
      

      Restart your shell session by exiting and reentering it, and you are finally ready to start using Bun. At this point you can verify your installation by checking the Bun version:

      bun -v
      
      0.1.5

      Example of a Bun Project

      Like NPM, Bun can be used to create and manage application projects. To give you an idea of Bun’s capabilities, the next series of steps walk you through creating and running a React application with Bun.

      The example adds a simple analog clock widget to the base React template, which lets you see more of how Bun manages project dependencies.

      1. Create a new Bun project. This is done by giving the bun create command with a template name and project folder.

        You can get a list of some useful available templates by running the create command without any arguments:

        bun create
        

        For this example, create your project from the React template, and give the project a directory of example-react-app, like this:

        bun create react ./example-react-app
        
      2. Afterward, be sure to change into the new project directory. The rest of these steps assume you are working out of this directory:

        cd example-react-app
        
      3. This already gives you a working React application, you just need to start it:

        bun dev
        
      4. You can see the application in action by navigating to localhost:3000 in your browser.

        To see the application remotely, you can use an SSH tunnel.

        • On Windows, use the PuTTY tool to set up your SSH tunnel. Follow the appropriate section of the
          Setting up an SSH Tunnel with Your Linode for Safe Browsing guide, replacing the example port number there with 3000.

        • On macOS or Linux, use the following command to set up the SSH tunnel. Replace example-user with your username on the application server and 192.0.2.0 with the server’s IP address:

          ssh -L3000:localhost:3000 [email protected]
          

        Default React application

      5. Use the CTRL+C key combination to stop Bun when you are finished viewing the application.

      6. Add an NPM package to your project. You can do so using the bun add command followed by the package name.

        This example uses the react-clock package, which allows you to easily render an analog clock for your React application:

        bun add react-clock
        
      7. The src/App.jsx file is the basis for the default React application. Open the file and incorporate the react-clock:

        nano src/App.jsx
        
      8. Replace the contents of src/App.jsx with the example file below. You can see the relatively simple modifications made to this file to incorporate the react-clock. The modified areas are prefaced with explanatory comments:

        File: src/App.jsx
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        
        import logo from "./logo.svg";
        import "./App.css";
        
        // Import React modules to be used by react-clock.
        import React, { useEffect, useState } from 'react';
        
        // Import react-clock and its CSS file.
        import Clock from 'react-clock';
        import 'react-clock/dist/Clock.css';
        
        function App() {
            // Define a state variable for the clock value; initialize it with the
            // current date-time.
            const [clockValue, setValue] = useState(new Date());
        
            // Define an effect that updates the clock's value periodically.
            useEffect(() => {
                const clockInterval = setInterval(() => setValue(new Date()), 1000);
        
                return () => {
                    clearInterval(clockInterval);
                };
            }, []);
        
            // Add to the default layout a <Clock/> tag for rendering the clock;
            // give it the clockValue to display.
            return (
                <div className="App">
                    <header className="App-header">
                        <img src={logo} className="App-logo" alt="logo" />
                        <h3>Welcome to React!</h3>
                        <Clock value={clockValue} />
                    </header>
                </div>
            );
        }
        
        export default App;
      9. Press CTRL+X to exit Nano, then Y to save, and Enter to confirm.

      10. Start up the application with Bun again:

        bun dev
        

        Once again, you should be able to visit the project by navigating to localhost:3000 in a web browser. Now you should see the default application modified with an analog clock.

        React application with an analog clock

      Conclusion

      Now that you have a footing with the Bun runtime, you can start exploring and seeing all it has to offer. With its built-in bundling and transpiling, you can create and execute projects with simpler tooling, plus the benefits of Bun’s incredible performance.

      Keep learning about Bun through the links below, as well as through the
      official documentation.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      How to Learn JavaScript… Fast


      Getting started with web development can seem intimidating. That’s because designing a website requires a mastery of multiple coding languages. If you’re an aspiring developer or designer, you might know that JavaScript is essential knowledge, but you may be unsure about where to begin acquiring this skill.

      Luckily, there are plenty of simple ways to learn JavaScript. You can find tons of free resources online to help you become an expert in this programming language. From lessons to projects and educational games, you’ll likely discover something that suits your particular learning style.

      In this article, we’ll introduce you to JavaScript and what it is typically used for. Then, we’ll recommend some helpful websites that you can use to start learning JavaScript for free. Let’s get to it!

      A Brief Introduction to JavaScript

      JavaScript, commonly abbreviated as ‘JS’, is a programming language primarily used to create complex features on websites. HTML, CSS, and JavaScript make up the framework of web design.

      You can think of HTML as the most basic component, CSS as defining fundamental visual elements, and JavaScript as the code that handles the most advanced features. For instance, JavaScript is responsible for most interactive content on the web.

      For example, browser games function thanks to JavaScript events. When you use an interactive map, you’re looking at JS as well. Features like clicking and dragging routes, loading local data, and even animations depend on this core language.

      Google Maps usage of JavaScript

      Essentially, HTML and CSS are used to define the basic look and makeup of elements on the web. JavaScript allows those elements to do more than just statically display information on the screen.

      Furthermore, JavaScript is used to animate objects both large and small on the web. This can be as simple as a notification icon for an app or as complicated as a weather radar map. Essentially, JavaScript controls how CSS elements function in order to create powerful animations with only a few lines of code.

      You might want to think of JavaScript as the conductor of an orchestra. HTML is the instruments, CSS is the performers, and JavaScript is running the show.

      Why You Might Want to Consider Learning JavaScript

      As we mentioned before, JavaScript is one of the three primary coding languages on the internet. Simply put, pretty much all web designers will likely need to learn JavaScript in order to create interactive content for the front end of websites. This type of web design can be as simple as a carousel for an image gallery or as complicated as an application with server-side API.

      In a nutshell, if you want to reap all the benefits of creating websites from scratch, and also incorporate modern features into your designs, you’ll need to know JavaScript. Virtually all websites use JavaScript to some extent.

      Whether it’s as a hobby or for professional reasons, learning HTML, CSS, and finally JavaScript can be a lot of work. However, as our world becomes increasingly digital, the demand for skilled coders continues to grow. As such, your efforts will likely pay off in the long run.

      How to Learn JavaScript Fast (2 Ways)

      Now that you have a sense of just how important JavaScript is, let’s go over two ways you can learn it, and fast! Keep in mind that JavaScript likely isn’t something you can completely master in a weekend.

      There is quite a lot to learn when it comes to this essential programming language. In any case, the following free resources will get you started with the basics, and even allow you to further hone your skills in fun and creative ways. Let’s dive right in!

      1. Take an Online Course

      Some web developers learn their trade by earning a computer science or engineering degree at a university. Still, there are plenty of free online courses only a few clicks away.

      In fact, web development has a long history of welcoming self-taught designers and programers. Here are three fast and free options to start learning JavaScript today.

      Learnjavascript.online

      The downside of passive methods of learning such as reading a textbook or watching a how-to video is that you don’t get hands-on practice. You can try to apply what you read or watched on your own, but this can be hard without guidance.

      Learnjavascript.online is an interactive environment that allows you to read short tutorials and then experiment with real coding, all within your browser. The fact that you are able to learn and immediately apply that knowledge in a real-world application can make it very effective:

      LearnJavaScript.online

      The first seven chapters are totally free. After that, you can unlock the entire collection of lessons by paying a one-time fee.

      Scrimba

      Scrimba uses interactive screencasts to teach a variety of lessons and guide you in creating your own applications. There are over 140 challenges to tackle and three projects, including coding your own Blackjack game:

      Scrimba JavaScript projects

      This platform uses a ‘learn by doing’ approach to things right from the start. With Scrimba, you won’t find any boring lessons or theory, just information about how to apply coding to solve problems. Keep in mind that it’s recommended that you take the HTML & CSS crash course (also free) before learning JavaScript.

      Free Code Camp

      Free Code Camp has a ton of great online resources for learning how to code. Unsurprisingly, JavaScript is one of these offerings, and there are plenty of tools and lessons for you to dive into. After you learn the basics, you can check out 40 beginner projects. This way, you can apply the concepts you have learned and solidify your knowledge.

      While Free Code Camp is a little less guided than the previous options, it provides you with a ton of valuable content, like a free course below:

      https://www.youtube.com/watch?v=/PkZNo7MFNFg

       

      2. Practice Using Educational Games

      Another great way to learn JavaScript is with educational games! Especially if you have any interest in game development yourself, interactive learning is a great way to stay motivated and have fun. Now, let’s review a few excellent educational games for aspiring JavaScript developers.

      JSRobot

      JSRobot is an amusing website that encourages you to actively use JavaScript right off the bat. While there isn’t much theory and background knowledge mixed in, you’ll have to write code to interact with your little robot:

      JSRobot start screen

      This unconventional learning technique may seem a bit silly at first, but it can likely help you get comfortable with writing code quickly and efficiently.

      Mastering coding isn’t just memorizing command lines and functions. It also requires an understanding of the logic behind that code. Therefore, JSRobot provides a good way to have fun while getting familiar with the reasoning behind JavaScript and learning a few commands along the way.

      CodeCombat

      CodeCombat offers users an intuitive approach to learning coding in a social setting. Its products provide a comprehensive curriculum, and are used in schools as an effective way to have fun while learning.

      Moreover, thanks to CodeCombat’s polished design and attractive fantasy world, you might even forget that you’re ‘studying’ while you use it:

      CodeCombat JavaScript game

      What really sets CodeCombat apart is that it doesn’t shy away from competition. The CodeCombat AI League allows you to put your JavaScript skills to the test against other coders.

      Untrusted

      Untrusted is a neat game inspired by old-school adventure games like Rogue and Nethack. It doesn’t teach you much about the fundamentals of JavaScript, but it is a great way to test your skills:

      Untrusted JavaScript game

      Rather than a series of lessons or instructions, Untrusted is about solving more open-ended puzzles using JavaScript.

      It is effective for learning to read JavaScript and understanding how it works. You will also get to tear apart someone else’s code to see how and why it functions. Once you have a little experience under your belt from the above methods, you can give Untrusted a try and see if you have what it takes to escape!

      Start Learning JavaScript for Free

      While learning advanced coding languages like JavaScript isn’t easy, free digital resources make it highly accessible. With a bit of motivation and quality online tools, you can learn to create a website that employs modern JavaScript features all on your own.

      We recommend starting by learning the basics with learnjavascript.online or Scrimba. Then you can follow up with lessons and activities from Free Code Camp. If you would prefer to learn with interactive games, try JSRobot for a fun introduction to JavaScript logic. After that, you can progress to more advanced challenges using Untrusted and CodeCombat.

      As you get started on your journey to become a WordPress developer, you’ll likely need a quality web host for all your projects. If that’s the case, we urge you to consider shared hosting with DreamHost. Our affordable plans include a domain, SSL certificate, privacy protection, and much more!

      Web Hosting That Powers Your Purpose

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $1.99/mo.

      shared hosting



      Source link

      A Javascript Objects Tutorial


      Objects play a fundamental role in JavaScript and appear just about everywhere throughout the language. This tutorial explains what JavaScript objects are and discusses object properties, methods, and prototypes. Each topic includes examples to illustrate their concepts.

      Before You Begin

      This guide’s JavaScript examples were originally run in the Node.js interpreter. You can use our
      How to Install and Use the Node Version Manager NVM
      guide to install Node.js on your computer.

      Alternatively, you can use your web browser’s JavaScript console to run this guide’s example JavaScript code.

      • If you are using Chrome, refer to Google’s
        Run JavaScript in the Console
        documentation to learn how to access their developer tools..

      • If you are using Firefox, refer to Mozilla’s
        Browser Console
        documentation to learn how to access their developer tools..

      What Are JavaScript Objects?

      The object is the fundamental data type in JavaScript, outside of primitive data types like numbers, strings, booleans, etc.

      An object is a collection of properties. A property is a key-value pair. In JavaScript, nearly anything can be a property. This includes not just primitive data types, but also functions and other objects.

      The next couple of sections further explain JavaScript objects, properties, and methods. They also provide examples on how to use JavaScript objects.

      JavaScript Object Properties

      Objects consist of zero or more properties. These can be either primitive data types (boolean, number, string, etc.), methods (that is, functions operating within an object), or other objects.

      Each property has a key, which can be an identifier, a number, or a string. Most of the time, identifiers are used, like in the example below of a house object:

      const house = {
          address: "123 Street Rd",
          bedrooms: 2,
          baths: 1.5,
          vacant: true,
          phoneNumber: "123-456-7890",
          inquire:  function() {
              console.log("Calling " + this.phoneNumber + "....");
          }
      };
      

      Typically, you access properties using dot notation. The example accesses the value of the address property:

      house.address;
      
      '123 Street St'

      You can also use bracket notation, as shown in the example below. Sometimes, bracket notation is required, like when a property’s key is a number or when you want to reference a key using a variable:

      let currentKeyOfInterest="vacant";
      house[currentKeyOfInterest];
      
      true

      If you want to list all of the properties of an object, you can use the Object.keys method:

      Object.keys(house);
      
      [ 'address', 'bedrooms', 'baths', 'vacant', 'phoneNumber', 'inquire' ]

      The fact that the method returns an array makes it useful if you want to iterate through an object’s properties. The example JavaScript for loop iterates over the keys of the house object created at the beginning of this section:

      for (const key of Object.keys(house)) {
          if (typeof house[key] != 'function') {
              console.log("==\t" + key.padEnd(16) + "\t=>\t\t" + String(house[key]).padEnd(16) + "\t==\t");
          }
      }
      
      ==  address             =>      123 Street St       ==
      ==  bedrooms            =>      2                   ==
      ==  baths               =>      1.5                 ==
      ==  vacant              =>      true                ==
      ==  phoneNumber         =>      123-456-7890        ==

      JavaScript Object Methods

      Any property that defines a function is called a method. These properties allow objects to take an action. For example, the inquire() method on the house object above prints a message to your JavaScript console. The example below calls the inquire() method:

      house.inquire();
      
      Calling 123-456-7890....

      Methods have direct access to an object’s other properties, making them especially useful for processing information on an object. You can see this in the inquire() method itself. It takes the phoneNumber property from its parent object and processes it into a message for the user.

      JavaScript Object Self Reference

      JavaScript’s this keyword gives objects a way to reference their own properties. You may have noticed its use in the inquire() method. The method is able to reference this.phoneNumber to work with the property’s assigned value.

      Below is another example. This example uses dot notation to extend the existing house object with a new method. That method then uses the this keyword to reference two properties on its parent object:

      house.bathToBedroomRatio = function() {
          return this.baths / this.bedrooms;
      }
      
      house.bathToBedroomRatio();
      
      0.75

      How to Create a JavaScript Object

      JavaScript offers you a few different ways to create objects. Each one has its own characteristics, so which one you use depends on your needs. The next sections walk you through each approach and explain their advantages with examples.

      Using an Initializer

      Object initializers provide the most direct approach for creating an object. You can see it used to declare the house example in the
      JavaScript Object Properties
      section. With this approach, you declare your object as a variable using object literal notation.

      It has the advantage of being straightforward and is useful when declaring a standalone object that does not need inheritance.

      Below is another example of the object initializer approach:

      const socrates = {
          name: "Socrates",
          role: "Philosopher",
          fingers: 10,
          mortal: true
      };
      

      Using the Object.create() Method

      The Object.create() method allows you to create new objects from an existing object, which becomes the new object’s prototype.

      This method is useful when you want multiple objects using the same base and when you want to declare objects programmatically.

      The example below creates a base Person object, then uses Object.create() method to make a specific object as an instance of that base. You then only have to define the properties that differ from the new object — name and role in this case.

      const Person = {
          name: "Nemo",
          role: "None",
          fingers: 10,
          mortal: true
      };
      
      const socrates = Object.create(Person)
      socrates.name = "Socrates"
      socrates.role = "Philosopher"
      
      socrates.name;
      socrates.role;
      
      'Socrates'
      'Philosopher'

      Using a Constructor

      An Object constructor is a function that defines an object type. You can then create a new object of that type using the new keyword.

      This approach gives objects a consistent underlying type, and it can create iterations of relatively complex objects with a single line of code.

      Like the Object.create() method, this approach is useful when you expect to have multiple objects from the same base or want to create objects programmatically. Using a constructor function lets you use more complex operations when initializing an object.

      The example below defines the type Person through an object constructor function. With the new keyword, the example then declares two new objects using the constructor. Despite the objects having five properties, the constructor only requires two arguments (the third is optional):

      function Person(name, role, fingers) {
          this.name = name;
          this.role = role;
          this.fingers = fingers > 0 ? fingers : 10;
          this.mortal = true;
          this.greeting = function() {
              console.log("Hello, I'm " + this.name + ". I'm a " + this.role + ", and have " + this.fingers + " fingers.");
              if (this.mortal) {
                  console.log("And, as you would expect, I'm mortal.");
              } else {
                  console.log("And, as impossible as it seems, I'm immortal.");
              }
          }
      }
      
      const socrates = new Person("Socrates", "Philosopher");
      const galileo = new Person("Galileo", "Astronomer", 7);
      
      socrates.greeting();
      galileo.greeting();
      
      Hello, I'm Socrates. I'm a Philosopher, and have 10 fingers.
      And, as you would expect, I'm mortal.
      
      Hello, I'm Galileo. I'm a Astronomer, and have 7 fingers.
      And, as you would expect, I'm mortal.

      You can even extend your constructors using additional constructors. Below, a Philosopher constructor extends the Person constructor defined above:

      function Philosopher(name, fingers, branch) {
          Person.call(this, name, "Philosopher", fingers);
          this.branch = branch;
          this.greeting = function() {
              console.log("Hello, my name is " + this.name + ", and I'm a " + this.branch + " " + this.role + ".");
          }
      }
      
      const seneca = new Philosopher("Seneca", 10, "Stoic");
      
      another_socrates.greeting();
      
      Hello, my name is Seneca, and I'm a Stoic Philosopher.

      How Does JavaScript Object Inheritance Work?

      JavaScript objects are able to inherit both types and properties from parent objects. You can see this with both the Object.create() and the object constructor examples above. This is due to JavaScript’s prototype system which is discussed in the next section.

      JavaScript Object Prototypes

      Every JavaScript object holds a reference to at least one other object, called its prototype. Even the most basic object has Object as its prototype, but other objects can inherit prototypes from parent objects or from constructor functions.

      Below are two examples showing how an object can be given a prototype, one using Object.create() and the other using an object constructor. Each example uses the following Animal object for the prototype:

      const Animal = {
          name: "",
          kingdom: "Animalia",
          phylum: "Chordata",
          class: "Mammalia",
          family: "",
          genus: "",
          species: ""
      };
      
      • Objects created using the Object.create() method automatically have the parent object as a prototype. You can see from the output below that only the three properties reassigned for the indus_dolphin object show up on that object instance. All of the other properties are stored on the prototype, Animal:

          const indus_dolphin = Object.create(Animal);
          indus_dolphin.name = "Indus River Dolphin";
          indus_dolphin.family = "Platanistidae";
          indus_dolphin.genus = "Platanista";
          indus_dolphin.species = "Platanista minor";
        
          Object.keys(indus_dolphin);
          Object.getPrototypeOf(indus_dolphin);
        
        [ 'name', 'family', 'genus', 'species' ]
        {
          name: '',
          kingdom: 'Animalia',
          phylum: 'Chordata',
          class: 'Mammalia',
          family: '',
          genus: '',
          species: ''
        }
      • Objects created using object constructors receive values from the constructor’s prototype property. In this example, the constructor assigns the provided values. Then, a prototype is given for the constructor, which provides the resulting object, ganges_dolphin, with a prototype object:

          function Platanista(species_name, species) {
              this.name = species_name;
              this.species = species;
          }
        
          Platanista.prototype = Animal;
          Platanista.prototype.family = "Platanistidae";
          Platanista.prototype.genus = "Platanista";
        
          const ganges_dolphin = new Platanista("Ganges River Dolphin", "Platanista gangetica");
        
          Object.keys(ganges_dolphin);
          Object.getPrototypeOf(ganges_dolphin);
        
        [ 'name', 'species' ]
        {
          name: '',
          kingdom: 'Animalia',
          phylum: 'Chordata',
          class: 'Mammalia',
          family: 'Platanistidae',
          genus: 'Platanista',
          species: ''
        }

      Each object holds a reference to its parent prototype. This ends up creating what is called a prototype chain, connecting back from one prototype to the next. This continues until the Object prototype is reached. (Object itself actually has null as a prototype, which technically is what ends the prototype chain.)

      So, for the indus_dolphin object above, the prototype chain would be: indus_dolphin -> Animal -> Object.

      Objects can access properties from their prototype chains. When you try to access a property on an object, JavaScript starts by looking on the object itself. If it does not find the property there, JavaScript moves backward through each prototype in the chain. It keeps doing this until it either finds a prototype with the property or reaches the end of the chain.

      For example, the first of the commands below fetches the name property off of the ganges_dolphin object directly. But the second command needs to look on the prototype object to find the kingdom property. Finally, the valueOf method actually belongs to the Object prototype:

      ganges_dolphin.name
      ganges_dolphin.kingdom
      ganges_dolphin.valueOf()
      
      'Ganges River Dolphin'
      'Animalia'
      { name: 'Ganges River Dolphin', species: 'Platanista gangetica' }

      Conclusion

      JavaScript objects underpin much of the power available in the language. Objects give you access to their properties and methods. You can extend Objects after creating them and also create new Objects based off of existing ones. This guide provided an introduction to the main concepts behind JavaScript objects, including constructors, the this keyword, object inheritance.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link