Skip to content

Simple Prototype

Published: at 12:00 PM

Prototypes in JavaScript:

Let’s breakdown of the Code below:

function Foo(params1) {
  this.params1 = params1;
}

Prototype Inheritance:

Accessing Inherited Properties:

All Javascript Object inherit properties and methods from prototype.

Let’s dive in for real world, firstly Create Object Constructor

function Foo(params1) {
  this.params1 = params1;
}

Call property with new instance

const instance = new Foo("Params 1");
console.log(instance.params1);
// ---- output: Params 1

We can not add new property to existing Object Constructor

Foo.newProperty = "This is new Property";
console.log(instance.newProperty);
// ---- output: undefined

And last we can add new property to Object Constructor

Foo.prototype.bar = "This is new Bar";
console.log(instance.bar);
// ---- output: This is new Bar

For complete codes

function Foo(params1) {
  this.params1 = params1;
}

/**
 * Create new instance as representative of Foo
 * all Foo's stuff will be inherits to new instance
 */
const instance = new Foo("Params 1");

// take property default
console.log(instance.params1);
// ---- output: Params 1

// can not add new property
Foo.newProperty = "This is new Property";
console.log(instance.newProperty);
// ---- output: undefined

// add new property
Foo.prototype.bar = "This is new Bar";
console.log(instance.bar);
// ---- output: This is new Bar

Key Points:

Thank you for reading this article, I hope you find it useful. Happy coding! 🔥