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.