in the last post we talked about the basics of oop in Javascript.
in this post we will explain constructor functions in more detail and add some methods to our blueprint that we created
How constructor functions work
we learned that to create an object from our blueprint we created we do:
const customer = new Customer("Alex", "alex@gmail.com", "12", {});
what's strange about this is that new keyword used in the function call and it is important to understand why we use it.
the new keyword does 3 things:
- it creates a new empty object
- it calls the function with the this keyword set to that new empty object
- it makes the function return that object after execution
this explains why we attach the props to the this object inside the function
summary:
the function is called with the this keyword set to an empty object, it attaches the passed props to that object, it returns that object with all the props without using a return statement
now that you understand how it all works try to make the Food constructor function with a name, description and an image.
Adding methods to the constructor function
we will add 2 methods to the Customer function, one for changing settings and one for ordering a meal
function Customer(name, email, password, settings, cart) {
this.name = name;
this.email = email;
this.password = password;
this.settings = settings;
this.cart = cart;
this.setSettings = function(newSettings) {
this.settings = newSettings;
}
this.orderFood = function(food) {
console.log(`ordering ${food}`);
}
}
as you can see adding methods is easy, now let's see them in action
customer.setSettings({ notifications: true });
customer.orderFood('Pizza'); // ordering Pizza
however adding methods this way is not the best, if you have few instances this should be ok but if you have a lot of instances it's going to be a problem because it will consume more memory than needed.
in the next post we will discuss a better way of adding methods
note: feel free to add more information or give feedback in the comments
Top comments (0)