Categories
JavaScript Answers

How to add method to object with JavaScript?

Spread the love

Sometimes, we want to add method to object with JavaScript.

In this article, we’ll look at how to add method to object with JavaScript.

How to add method to object with JavaScript?

To add method to object with JavaScript, we can add it to the prototype of the constructor.

For instance, we write

function Foo() {}
Foo.prototype.bar = function () {};

const x = new Foo();
x.bar();

to create the Foo constructor with

function Foo() {}

Then we add the bar instance method to its prototype with

Foo.prototype.bar = function () {};

Then we instantiate a Foo object and called the Foo instance’s bar method with

const x = new Foo();
x.bar();

Conclusion

To add method to object with JavaScript, we can add it to the prototype of the constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *