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
When some one searches for his required thing, thus he/she wants to be available
that in detail, therefore that thing is maintained over here.
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.
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
Excellent submit, very informative. I ponder why the other experts of this sector don’t realize this. You should continue your writing. I’m confident, you have a huge readers’ base already!
I do consider all of the ideas you’ve presented on your post. They are very convincing and can certainly work. Nonetheless, the posts are too quick for starters. May just you please extend them a little from next time? Thanks for the post.
Okay! Thanks, have a nice day
Pretty section of content. I just stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement you access consistently quickly.
Thank you
I was suggested this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You’re incredible! Thanks!
Thank you!
Its like you learn my thoughts! You seem to understand so much about this, such as you wrote the guide in it or
something. I feel that you just can do with some percent to drive the message house a little bit, but other than that, this is magnificent blog.
A fantastic read. I’ll certainly be back.
Thank you!
It’s perfect time to make a few plans for the long run and
it’s time to be happy. I’ve learn this post and if I may I desire to counsel you few attention-grabbing things or suggestions.
Maybe you can write next articles relating to this article.
I wish to learn more issues about it!
Thanks! Yes, we are writing blogs on daily basis!
Ahaa, its good discussion about this paragraph at this place at this blog, I have read all that, so now me also commenting at this place.