Creating A Property
As previously discussed, a property is just a variable for an object. Creating a property in an object is different than creating a variable in general. Let’s update your Car class to this.
this.color = 'white';
You’ll notice you don’t have to use the var keyword. Instead, you’re using the this keyword. The this keyword is a way to refer to the class to itself. Normally you would refer to an object by it’s name or the name of it’s instance, but since you’re already inside the class, you have to use the this keyword when talking about the object itself.
Using dot notation, you give your property a name and then it’s value. It’s optional to give your property a value. In our case, we created a property called color and gave it the initial value white.
Whenever someone creates an instance of the Car class, then the color is set to white every time. Let’s try accessing this property in our script. Add this line of code into your script.
document.write( honda.color );
You should see white outputted into the document. Did you know you could also update the value of this property by doing something like this?
honda.color = 'red';
The great thing is that this only affects the current instance. If you created another instance like ford, then you can change that car’s color to blue and it wouldn’t affect the honda instance.
Creating A Method
Accessing a property directly is not practical. It’s better to use getter and setter methods. What are getter and setter methods? This is the technical term for methods that update or grab a property for you. It’s safer to do it this way as it allows you to filter data before doing anything to the property itself.
Let’s create these 2 methods in our Car class. Update your Car class to this.
this.color = 'white';
this.setColor = function setColor( newColor )
this.color = newColor;
this.getColor = function getColor()
document.write( "This car's color is " + this.color );
Creating a method is similar to creating a property. The only difference is that you define a function instead of setting a value. The process for creating a function is the same for creating a function in a class.
You’ll notice in the setColor() method, it has 1 parameter. which is the value for the new color. Then, you update the color property with the value passed into the setColor() method.
The getColor() method simply outputs the current color to the document. Just like creating a property, you can use the this keyword to access the object’s property and update it anytime.
Update your script to this.
honda.setColor( 'blue' );