One place for hosting & domains

      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

      Accessing the Document Object Model with JavaScript


      The Document Object Model (DOM) is a language-agnostic interface that provides access to an HTML document’s structure and content. JavaScript is often the language used to access the DOM in order to generate dynamic and interactive web pages.

      This guide provides an overview of the Document Object Model and shows you how to interact with it using a series of JavaScript examples.

      Before You Begin

      The examples in this guide use a web browser’s developer tools to view the DOM and interact with a JavaScript console. To get the most out of the information in this guide, follow along in your own Chrome or Firefox browser.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.

      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      What Is the Document Object Model?

      The Document Object Model (DOM) is an interface that provides access to an HTML document’s structure and content. The DOM represents the elements and content of an HTML document as nodes and objects. The DOM representation can then be accessed and modified by JavaScript and other scripting languages.

      Essentially, the DOM is what allows web pages to become dynamic. Languages like JavaScript work with the nodes that make up the DOM to dynamically and interactively change a web page’s presentation.

      There are many ways of displaying the DOM. One of the most widely used ways is the HTML format. When you open your browser’s Inspect dashboard, you can view the HTML representation of a web page. The example below shows the HTML markup for a simple web page.

      <!DOCTYPE html>
      <html>
        <head>
          <title>Example Page</title>
        </head>
        <body>
          <p>Example page content.</p>
        </body>
      </html>
      

      How the DOM Differs from HTML Source Code

      The DOM itself is not equivalent to a web page’s HTML source code. Instead, the DOM is a representation of how a web page is displayed in the moment that it is accessed.

      To illustrate how the DOM and HTML source code can differ, the example below displays an HTML source file. The HTML file includes a JavaScript function that adds additional HTML elements to the page once the page loads.

      File: example-page.html
       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
      
      <!DOCTYPE html>
      <html>
        <head>
          <title>Example Page</title>
          <script>
              function addExampleList() {
                  const exampleList = document.createElement("ul");
      
                  const exampleListItem1 = document.createElement("li");
                  const exampleListItem1Text = document.createTextNode("First item");
                  exampleListItem1.appendChild(exampleListItem1Text);
      
                  const exampleListItem2 = document.createElement("li");
                  const exampleListItem2Text = document.createTextNode("second item");
                  exampleListItem2.appendChild(exampleListItem2Text);
      
                  exampleList.appendChild(exampleListItem1);
                  exampleList.appendChild(exampleListItem2);
      
                  document.body.appendChild(exampleList);
              }
          </script>
        </head>
        <body onload="addExampleList();">
          <p>Example page content.</p>
        </body>
      </html>

      Once the HTML page is loaded and the JavaScript runs, the DOM representation of the HTML source above resembles the code displayed below. The JavaScript has been left out to make the resulting HTML easier to read. The HTML now includes an unordered list (<ul>...</ul>) with two list items (<li>...</li>).

      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
              <script>[...]</script>
          </head>
          <body onload="addExampleList();">
              <p>Example page content.</p>
              <ul>
                  <li>First item</li>
                  <li>Second item</li>
              </ul>
          </body>
      </html>
      

      Since the DOM is concerned with displaying the current state of an HTML page, it now displays the new HTML elements that were added to the page by the JavaScript. The DOM always reflects any additions, subtractions, or other modifications that happen to a web page. This characteristic is what enables the DOM to make web pages dynamic.

      The Document Object Model and JavaScript

      Most often, JavaScript is how web developers interact with the DOM. JavaScript is able to access the DOM with the document object and the nodes nested under it.

      The next sections explain what the document object is and the parts that make it up.

      Document Object

      To work with the DOM, client-side JavaScript provides the document object. This object includes properties and methods to access and modify the DOM.

      The previous section included some examples of the document object in action. Below are two additional commands that show more of the document object’s features.

      1. The document object’s properties provide information about the HTML document or access to its nested nodes. They also allow you to modify characteristics of the DOM as shown in the example below:

        document.body.style.backgroundColor = "blue";
        

        The example JavaScript accesses the document object’s backgroundColor property and sets its value to "blue". The web page it modifies should now have a blue background. The DOM representation of the change looks as follows:

        <!DOCTYPE html>
        <html>
            <head>
                <title>Example Page</title>
                <script>[...]</script>
            </head>
            <body onload="addExampleList();" style="background-color: blue;">
                <p>Example page content.</p>
                <ul>
                    <li>First item</li>
                    <li>second item</li>
                </ul>
            </body>
        </html>
        

        The color blue is assigned to the <body> element using the style attribute.

      2. The document object has several methods that do everything from provide access to specific nodes to add new nodes to the DOM. In the example below, the getElementsByTagName() method grabs every HTML element with the tag name, <li>. The JavaScript loops through those elements, and then outputs each elements textContent attributes.

        for (item of document.getElementsByTagName("li")) {
            console.log(item.textContent);
        }
        

        Using the for loop above, the JavaScript console should display the following output:

        First item
        Second item

      Nodes and Elements

      The document object contains numerous other objects that all make up the DOM. These objects are called nodes. Nodes include everything from HTML elements, to attributes, to text.

      You are likely to work most frequently with element nodes. DOM element nodes correspond to a web page’s HTML elements. They allow you to access and manipulate the building blocks of a web page.

      The script used in the
      How the DOM Differs from HTML Source
      section added a <ul> element and <li> elements to the page. This added the following two kinds of nodes to the page:

      • Element nodes, which were created using the document.createElement method.
      • Text nodes, created with the document.createTextNode method.

      Each part of the document object is actually a node of some kind or other. Additionally, each node inherits common properties, like the appendChild method, which lets elements add text nodes.

      The document object does more than just let you extend the DOM. For instance, you can also use it to navigate the DOM and make precise modifications to it. The script below demonstrates how these modifications can be made to the DOM. Access the
      example-page.html
      page in your browser. Then, open your browser’s JavaScript console, and enter in the following JavaScript:

      const listItems = document.getElementsByTagName("li");
      
      for (item of listItems) {
          const newTextNode = document.createTextNode(item.textContent.replace("item", "thing"));
      
          item.innerHTML = "";
          item.appendChild(newTextNode);
      }
      

      As a result, the DOM is updated and the text, item, contained within the <li> tags is updated to thing.

      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
              <script>[...]</script>
            </head>
            <body onload="addExampleList();">
              <p>Example page content.</p>
              <ul>
                  <li>First thing</li>
                  <li>Second thing</li>
              </ul>
          </body>
      </html>
      

      See our guide
      Traversing the Document Object Model with JavaScript
      , to learn about other built-in document object methods.

      Conclusion

      The DOM provides an interface to an HTML web page. This enables you to manipulate the structure and content of a web page using scripting languages, like JavaScript. This guide introduced you to the DOM and demonstrated how JavaScript is used to add, modify, and remove HTML elements from a web page.

      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

      Automatic Updates and Maintenance Windows


      Fully managed cloud database clusters built on top of Linode’s trusted and reliable platform.

      As part of the Managed Database service, the database cluster is updated regularly. This includes security updates and patches for the underlying operating system. These updates occur on a user-configurable maintenance window. By default, the maintenance window is set to start every week on Sunday at 20:00 UTC and lasts for 3 hours.

      Caution

      If your database cluster is configured with a single node, you will experience downtime during this maintenance window when any updates occur. It’s recommended that you adjust this window to match a time that will be the least disruptive for your application and users. You may also want to consider upgrading to a high availability plan to avoid any downtime due to maintenance.

      Note

      The database software is not updated automatically. To upgrade to a new version (such as from MySQL 5.7.30 or 8.0.25 to 8.0.26), consider deploying a new Managed Database with the version you wish to use. You can then
      migrate your databases
      from the original Managed Database cluster to the new one.

      View and Modify the Maintenance Window

      1. Log in to the
        Cloud Manager
        and select Databases from the left navigation menu.

      2. Select your Managed Database from the list. This opens the detail page for that database cluster.

      3. Navigate to the Settings tab.

      4. In the Maintenance Window section, you can view the day of the week the maintenance occurs, the time of day it starts, and if maintenance is performed on a weekly or monthly basis.

        • Day of Week: The day of the week that the maintenance will occur. The default is Sunday.
        • Time of Day (UTC): The time of day (in UTC) the maintenance window will start. The default is 20:00 UTC (8 PM). The maintenance window lasts for 3 hours.
        • Weekly or Monthly: Defines if the maintenance occurs once per week or once per month. The default is Weekly. If Monthly is selected, you can select if the maintenance should occur during the first, second, third, or fourth week of each month.
      5. To modify the maintenance window, make any changes you wish and click the Save Changes button.

      This page was originally published on



      Source link