This is an overview on how to create a basic object class in JavaScript.
JS Objects
JavaScript is not an object-oriented programming language. However, you can create 'objects' in JavaScript that behave similar to other OO languages.
Per the MDN Document, an object is a collection of properties.
JavaScript uses objects as a data type that provides a framework for how a particular item should behave. An instance method is used to define a specific instance's characteristics.
Syntax
class Dog {
constructor(name, breed, age, owner){
this.name = name;
this.breed = breed;
this.age = age;
this.owner = owner;
}
}
The Constructor Method
Every class uses the constructor method to instantiate a new instance of the object. In my example above, we pass in a name
, breed
, age
, and owner
when we create a new Dog
object. We set this
instance of Dog
to be equal to the variables passed in. The keyword this
refers to that particular instance of Dog
.
Note that the above is just the method for creation; no instance of Dog
has yet been created.
To better understand the object's properties versus the arguments given, you could alternatively set up your constructor per the below. Note that dogName
, dogBreed
, ... are the arguments passed in, and .name
, breed
are the properties each Dog
instance will obtain.
class Dog {
constructor(dogName, dogBreed, dogAge, dogOwner){
this.name = dogName;
this.breed = dogBreed;
this.age = dogAge;
this.owner = dogOwner;
}
}
Create an Object
Create a new object with the new
keyword, followed by the class name. I prefer to store a new object in a variable so we can use it later to modify.
dog1 = new Dog("Fluffy", "Golden Retriever", "4", "Jane Smith")
// Dog {name: 'Fluffy', breed: 'Golden Retriever', age: '4', owner: 'Jane Smith'}
Retrieve an Object's Data
With our variable, dog1
, we can access that variable's data by calling their properties.
dog1.name
// 'Fluffy'
dog1.breed
// 'Golden Retriever'
dog1.age
// '4'
Give an Object Behavior with Instance Methods
An instance method takes action on that particular Dog
instance it is called on.
In the example below, the method named bark
gives each instance of Dog
the ability to "woof" when called. Similarly, the ageUp
method increases that specific dog's age by 1 and returns its new age.
class Dog {
constructor(name, breed, age, owner){
...
}
bark(){
return `${this.name} the dog says woof!`;
}
ageUp(){
this.age += 1;
return this.age;
}
}
dog1.bark()
// "Fluffy the dog says woof!"
dog1.ageUp()
// 5
Top comments (0)