JavaScript | Working with Objects | angular

JavaScript | Working with Objects | angular

There are several ways to create objects in JavaScript. The following example gives a simple example to get started.

let myData = new Object();
myData.name = "Adam";
myData.weather = "sunny";
console.log("Hello " + myData.name + ".");
console.log("Today is " + myData.weather + ".");
I create an object by calling new Object(), and I assign the result (the newly created object) to a
variable called myData. Once the object is created, I can define properties on the object just by assigning
values, like this:
...
myData.name = "Adam";
...

Prior to this statement, my object doesn’t have a property called name. When the statement has executed, the property does exist, and it has been assigned the value Adam. You can read the value of a property by combining the variable name and the property name with a period, like this:

...
console.log("Hello " + myData.name + ".");
...

The result from the example is as follows:

Hello Adam.

Today is sunny.

Using Object Literals

You can define an object and its properties in a single step using the object literal format, as shown in the following example.

let myData = {
 name: "Adam",
 weather: "sunny"
};

console.log("Hello " + myData.name + ". ");
console.log("Today is " + myData.weather + ".");

Each property that you want to define is separated from its value using a colon (:), and properties are separated using a comma (,). The effect is the same as in the previous example, and the result from the listing is as follows:

Hello Adam.

Today is sunny.

Using Functions as Methods

One of the features that I like most about JavaScript is the way you can add functions to objects. A function defined on an object is called a method. The following example shows how you can add methods in this manner.

let myData = {
 name: "Adam",
 weather: "sunny",
 printMessages: function () {
 console.log("Hello " + this.name + ". ");
 console.log("Today is " + this.weather + ".");
 }
};
myData.printMessages();

In this example, I have used a function to create a method called printMessages. Notice that to refer to the properties defined by the object, I have to use this keyword. When a function is used as a method, the function is implicitly passed the object on which the method has been called an argument through the special variable this. The output from the listing is as follows:

Hello Adam.

Today is sunny.



Defining Classes

Classes are templates that are used to create objects that have identical functionality. Support for classes is a recent addition to the JavaScript specification intended to make working with JavaScript more consistent with other mainstream programming languages, and classes are used throughout Angular development. The following example shows how the functionality defined by the object in the previous section can be expressed using a class.

class MyClass {
 constructor(name, weather) {
 this.name = name;
 this.weather = weather;
 }
 printMessages() {
 console.log("Hello " + this.name + ". ");
 console.log("Today is " + this.weather + ".");
 }
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();

JavaScript classes will be familiar if you have used another mainstream language such as Java or C#. The class keyword is used to declare a class, followed by the name of the class, which is MyClass in this case.

The constructor function is invoked when a new object is created using the class, and it provides an opportunity to receive data values and do any initial setup that the class requires. In the example, the constructor defines name and weather parameters that are used to create variables with the same names. Variables defined like this are known as properties.

Classes can have methods, which defined as functions, albeit without needing to use the function keyword. There is one method in the example, called printMessages, and it uses the values of the name and weather properties to write messages to the browser’s JavaScript console.

The new keyword is used to create an object from a class, like this:

...
let myData = new MyClass("Adam", "sunny");
...

This statement creates a new object using the MyClass class as its template. MyClass is used as a function in this situation, and the arguments passed to it will be received by the constructor function defined by the class. The result of this expression is a new object that is assigned to a variable called myData. Once you have created an object, you can access its properties and methods through the variable to which it has been assigned, like this:

...
myData.printMessages();
...

This example produces the following results in the browser’s JavaScript console:

Hello Adam.

Today is sunny.

Defining Class Getter and Setter Properties

JavaScript classes can define properties in their constructor, resulting in a variable that can be read and modified elsewhere in the application. Getters and setters appear as regular properties outside of the class, but they allow the introduction of additional logic, which is useful for validating or transforming new values or generating values programmatically, as shown in the following example.

Listing 6-5. Using Getters and Setters in the main.ts File in the src Folder
class MyClass {
 constructor(name, weather) {
 this.name = name;
 this._weather = weather;
 }
 set weather(value) {
 this._weather = value;
 }
 get weather() {
 return `Today is ${this._weather}`;
 }
 printMessages() {
 console.log("Hello " + this.name + ". ");
 console.log(this.weather);
 }
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();

The getter and setter are implemented as functions preceded by the get or set keyword. There is no notion of access control in JavaScript classes, and the convention is to prefix the names of internal properties with an underscore (the _ character). In the listing, the weather property is implemented with a setter that updates a property called _weather and a getter that incorporates the _weather value in a template string. This example produces the following results in the browser’s JavaScript console:

Hello Adam.

Today is sunny

Using Class Inheritance

Classes can inherit behavior from other classes using the extends keyword, as shown in the following example.

class MyClass {
 constructor(name, weather) {
 this.name = name;
 this._weather = weather;
 }
 set weather(value) {
 this._weather = value;
 }
get weather() {
 return `Today is ${this._weather}`;
 }
 printMessages() {
 console.log("Hello " + this.name + ". ");
 console.log(this.weather);
 }
}
class MySubClass extends MyClass {
 constructor(name, weather, city) {
 super(name, weather);
 this.city = city;
 }
 printMessages() {
 super.printMessages();
 console.log(`You are in ${this.city}`);
 }
}
let myData = new MySubClass("Adam", "sunny", "London");
myData.printMessages();

The extends keyword is used to declare the class that will be inherited from, known as the superclass or base class. In the listing, the MySubClass inherits from MyClass. The super keyword is used to invoke the superclass’s constructor and methods. The MySubClass builds on the MyClass functionality to add support for a city, producing the following results in the browser’s JavaScript console:

Hello Adam.

Today is sunny

You are in London



This Post Has 3 Comments

  1. Avatar

    Magnificent goods from you, man. I have take into
    accout your stuff previous to and you’re just too wonderful.

    I really like what you’ve obtained here, certainly like what you are stating and the best way through which you
    assert it. You are making it enjoyable and you continue
    to care for to keep it smart. I can’t wait
    to learn far more from you. This is really a tremendous
    website.

  2. Avatar

    I think this is one of the most vital info for me. Annd i
    am glad reading your article. Butt should remark on few general things, The wweb site style is
    perfect, the articles is really nice : D. Good job, cheers

Leave a Reply

Close Menu