This time, we will learn how to create an object.
You use function to specify the properties of an object, create a method to specify how to do that property, and finally the process of creating an object.
Let's listen to the car's analogy.
Cars have a common name, they have an engine, they have a manufacturer, they have a color, and these are properties.
Then start the car, run, etc. is a method.
And object creation means building a car.
In other words, if you specify an attribute, this is where your company's car is, what wheel is using the engine, what color is it, and how many people can ride it.
Methods run, stand, curve, etc.
Creating an object is equivalent to creating an Audi R8 at the factory.
So let's declare a property.
Attributes are created using function.
function makeCar(){ //Name of the function that defines the makeCar property. //As an example of making a car, I named it makeCar, //Use the name you want. //Properties are declared using this. //If you create a name attribute this.name; //This is defined. this.company; //Car color definition this.color; //Passenger this.numPeople; // //And print out a method of how to do it with these data. So that it is connected to the method. this.meth = showCar; //Declare the method named showCar in the property named meth. }
Now let's create the method. The role of this method is to show you where the car you're building is, how many people can ride, and what color it is.
In the property declaration source above, the part that invokes the method is this.meth = showCar; This is it.
So let's create a method called showCar.
Methods are defined using function just like property definitions.
Let's create a method as above and now make a car. This process is called creating objects.
Let's make AUDI R8.
First, declare a variable to create an object, use the new command and write the name of the function that declared the object property.
r8 = new makeCar();
And enter the name of the car as a value. this.name = "r8"
Let's see through an example.
So let's test it by example.
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>JavaScript</title> <script> function makeCar(){ this.name; this.company; this.color; this.numPeople; this.meth = showCar; } function showCar(){ document.write("name of car : "+this.name+"<br />"); document.write("maker of car : "+this.company+"<br />"); document.write("passener of car : "+this.numPeople+"<br />"); document.write("color of car : "+this.color+"<br />"); } r8 = new makeCar(); r8.name="R8"; r8.company = "AUDI"; r8.color = "white"; r8.numPeople = 2; r8.meth(); </script> </head> <body> </body> </html>
If you create an object other than r8, you can create another object in the same way as above.
In addition to the sources above, if you try it, another object will be created to show the information through the output method.
This concludes the tutorial on objects.