Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 27, 2022 09:29 pm GMT

object oriented programming in Javascript (part 2)

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", "[email protected]", "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


Original Link: https://dev.to/hacker4world/object-oriented-programming-in-javascript-part-2-22ce

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To