Gugusteh
Gugusteh

Reputation: 128

How to pass arguments to a function in a JS ES6 Class?

I am trying to create some ES6 classes to clear my javascript code. I am unsure about the way to pass arguments to functions inside a Class.

As I understood, the correct way is through the constructor but this would mean that they are bound once when I instanciate the class.

In the following example i'd like to pass an element elem to my function Categories.addCategory.

    class Categories {
        constructor(id, name) {
            this.id = id;
            this.name = name;
        }

        getName() {
            return this.name;
        }

        getId() {
            return this.id;
        }

        addCategory(elem) {
            $(elem).addClass('category');
        }
    }
Cat = new Categories(1, 'new products');
Cat.addCategory('#product1');

I also wonder if there is another way to pass arguments rather than only using the constructor.

Sorry if the question is unclear i'm fairly new to ES6 Classes and may have missed some core points.

Upvotes: 0

Views: 4509

Answers (2)

Melvin More
Melvin More

Reputation: 60

let categories = new Categories();
categories.id = 5;
categories.name = "Books";

Upvotes: 0

Joseph
Joseph

Reputation: 119887

It looks like you already know how to create instances off of a class. Now you just need to invoke the method from the instance, passing arguments as values between the parens of the invocation.

const instanceOfCategories = new Categories('12345', 'John')

instanceOfCategories.action('.your-selector')

You can have more than one argument, and the order you pass them is the order they'll arrive in the method.

Upvotes: 1

Related Questions