Prototype Pattern trong Javascript

Tram Ho

Prototype Pattern trong Javascript

In a flexible language like Javascript, you can apply a lot of different patterns. Depending on the circumstances we can apply. Object oriented programing or OOP, you’ve heard and used them a lot already. But in Javascript, we have another programing direction, called prototype. Now let’s try to see what prototypes are interesting and the benefits of using prototypes.

Prototype

This pattern is focused on helping create objects from a previous blueprint, and the following objects will inherit different methods and properties. This property is called prototype inheritance. When creating an object in ES6, you are familiar with class declarations. In ES5, we have another way is the function constructor. Suppose when writing a game we want to build a Warrior class as follows:

With the above method, 3 warriors were created. They share a common contructor, Warrior

Let’s say, now our warrior class wants to have different skills like bash, slash

Now how the warriors have their skills and spoiled each other. But here, each warrior has a unique skill, but obviously, this skill is identical. This is a waste when we check back

That’s why we need something like a constructor, which is the prototype

The above method is similar to the following writing method

Conclusion

However, this method will lose the Warrrior constructor. This is how the prototype has implemented its inheritance and sharing capabilities in javascript. Hopefully the next article I can continue to explore more interesting things. Thank you for following up

References

https://medium.com/better-programming/the-prototype-pattern-in-javascript-bfe9ff433e6c

Share the news now

Source : Viblo