Computer Science

Javascript Objects

Javascript objects are data structures that store data and functions together. They are used to represent real-world objects and concepts in code. Objects can be created using object literals or constructor functions.

Written by Perlego with AI-assistance

6 Key excerpts on "Javascript Objects"

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

    JavaScript

    Syntax and Practices

    For instance, a table lamp can be in a state of on or off and have a behavior of getting turned on and off. Here, on/off are one of the possible states, and turn on/off are the actions performed to change its state. Similarly, a cat has her state defined in terms of color, weight, size and breed. A cat's behavior is judged by what she does, i.e. meows, runs, scratches etc. This is how the state and behavior for an object together make it look and act like any real-world object. Quick exercise: Look at the physical objects around you and think about the different states they can be in; think about the different behavior they exhibit. If you were asked to model those objects, then how would you describe these states and behavior for those objects. Try for at least 10 different objects. This chapter discusses the concept of objects and how they differ from other programming languages in terms of declaration and usage. A detailed discussion on object's properties is provided followed by the concept of classes. Further prototypal inheritance for Javascript Objects is discussed, and the concept of inheritance with subclasses is discussed toward the end of the chapter. 3.1 Objects Objects are used to represent real-world entities, which makes programming a solution easier for the developer. Objects can store data in an organized and cohesive manner. Objects are the fundamental data type of JavaScript [67]. Almost everything in JavaScript is object oriented, except very few primitive data types; these primitives also have their wrapper objects as we have already discussed in previous chapters. The objects are variables that can contain multiple values as an unordered collection of data. These can be changed or mutated by using the object's reference. An object is used, denoted and handled by using the reference value assigned to it
  • Prototype and Scriptaculous in Action
    In most object-oriented programming languages, such as C++, Java, and C#, an Object will have a predefined set of members corresponding to its properties and methods. This set is defined by the class definition for the object, and it will remain constant throughout the lifetime of the object. In JavaScript, however, there are no class definitions as such, and an object can accept new members at any point in its life. In many ways, the JavaScript Object type is best thought of as an associative array or hash table.
    The most obvious expression of this is the fact that the dot notation usually associated with objects and the square-bracket notation associated with arrays are interchangeable in JavaScript. To define a value for an object’s property in Java, C#, etc., we would normally write something like this:
    myObject.something = "hello world"; In JavaScript, that notation works, but it can also be written as follows: myObject['something'] = "hello world";
    The net effect of the two statements is exactly the same—the value of a property called something is set to the string hello world. In Java or C#, the object would need to be defined as an instance of a class containing a property called something, of course, but in JavaScript, it isn’t so; if the property something was previously unset for our object, it will simply add it in.
    Extending a JavaScript object with new properties extends the state that it contains. More excitingly, extending it with new methods extends the behavior that it is capable of. Javascript Objects that we create ourselves can be extended in this way, and so can native objects. An object can be extended on a case-by-case basis, but the base definition for an entire type of object can also be extended. Prototype provides support for all of these capabilities, as we’ll see in the following sections.
    8.2.1. Creating an Object
    In simple JavaScript code, we can get by without using objects, but in any moderately complex project, using objects can help to structure our code considerably. In the first section of this book, we presented a web-based image gallery application. At the end of chapter 4
  • Secrets of the JavaScript Ninja, Second Edition

    7.1. Understanding prototypes

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

    Encapsulation

    Objects are central to the Object-Oriented Programming model, and they represent the typical expression of encapsulation , that is, the ability to concentrate in one entity both data (properties) and functions (methods), hiding the internal details.
    In other words, the encapsulation principle allows an object to expose just what is needed to use it, hiding the complexity of its implementation. This is a very powerful principle, often found in the real world that allows us to use an object without knowing how it internally works. Consider for instance how we drive cars. We need just to know how to speed up, brake, and change direction. We do not need to know how the car works in detail, how its motor burns fuel or transmits movement to the wheels.
    To understand the importance of this principle also in software development, consider the following code: var company = { name: "ACME Inc.", employees: [], sortEmployeesByName: function() {...} };
    It creates a company object with a name, a list of employees and a method to sort the list of employees using their name property. If we need to get a sorted list of employees of the company, we simply need to know that the sortEmployeesByName() method accomplishes this task. We do not need to know how this method works, which algorithm it implements. That is an implementation detail that encapsulation hides from us.
    Hiding internal details and complexity has two main reasons:
    • The first reason is to provide a simplified and understandable way to use an object without the need to understand the complexity inside. In our example, we just need to know that to sort employees, we have to call a specific method.
    • The second reason is to simplify change management. Changes to the internal sort algorithm do not affect our way to order employees by name. We always continue to call the same method. Maybe we will get a more efficient execution, but the expected result will not change.
  • Beginning JavaScript
    • Jeremy McPeak(Author)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    Person constructor serve the same purpose: to represent an individual person. The main difference is how the objects are created. Objects created from a constructor typically consume less of the computer’s memory than literal objects.
    Frankly, it’s a question you don’t have to worry about at this point in time. It’s more important to know how to create objects than using the correct approach. So practice both methods; create your own custom objects and reference types!

    SUMMARY

    In this chapter you’ve taken a look at the concept of objects and seen how vital they are to an understanding of JavaScript, which represents virtually everything with objects. You also looked at some of the various native reference types that the JavaScript language provides to add to its functionality.
    You saw that:
    • JavaScript is object-based—it represents things, such as strings, dates, and arrays, using the concept of objects.
    • Objects have properties and methods. For example, an Array object has the length property and the sort() method.
    • To create a new object, you simply write new ObjectType() . You can choose to initialize an object when you create it.
    • To set an object’s property value or get that value, you simply write objectName.objectProperty .
    • Calling the methods of an object is similar to calling functions. Parameters may be passed, and return values may be passed back. Accessing the methods of an object is identical to accessing a property, except that you must remember to add parentheses at the end, even when it has no parameters. For example, you would write objectName.objectMethod() .
    • The String type provides lots of handy functionality for text and gives you ways of finding out how long the text is, searching for text inside the string, and selecting parts of the text.
    • The Math type is created automatically and provides a number of mathematical properties and methods. For example, to obtain a random number between 0 and 1, you use the method Math.random()
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.