DEV Community

Cover image for The Prototype Pattern in JavaScript

The Prototype Pattern in JavaScript

jsmanifest on November 20, 2019

Find me on medium There are multiple design patterns that can be implemented in the JavaScript language, and in this post we will be going over th...
Collapse
 
emptyother profile image
emptyother

..which is equivalent to the code below, a typical class object in modern javascript. I prefer this over modifying prototype objects directly, just because it looks cleaner.

class Warrior { 
    constructor(name) {
        this.name = name;
        this.hp = 100;
    }
    bash(target) {
        target.hp -= 15;
    }
    omniSlash(target) {
        if(target.hp < 50) {
            return;
        }
        target.hp -= 50;
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lukaszs1 profile image
Lukasz

it is just syntactic sugar for above, which is very nice explanation of prototype pattern

Collapse
 
appalanaveen1 profile image
appalanaveen1

I am an experienced java developer trying to learn javascript, this post helped me a lot to understand the inheritance used in javascript, i read several posts, but everyone says "JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++)" and continue with syntax and examples etc..., but never told about what's the exact difference, here only i got exact answer what i am looking for days. Thanks a lot.

Collapse
 
jsmanifest profile image
jsmanifest

That is awesome, your welcome!

Collapse
 
fly profile image
joon

Very informational read, never understood why some experienced devs used prototypes, now I do and plan on doing the same. Thanks a lot for shedding light on the subject

Collapse
 
jsmanifest profile image
jsmanifest

Very glad to hear that!