1

I have please encountered the following example in a book of a declaration of a class inside a function argument, even though I have searched thoroughly online, could not find an explanation, what it does, what is declared, what is passed into the function, and when should I use it if at all (perhaps its a bad practice ?).

Thank you for your help and guidance !

function f(parameter1) {
    console.log(parameter1);
}

class ClassA {

}

f(class extends ClassA {

    render() {

    }
});

2 Answers 2

2

In javascript, class is just a syntax sugar for function, and just like function it's a first class value, which can be assigned, passed around etc.

let a = class {
    foo() {
        console.log('hey')
    }
};

new a().foo()

//

function x(klass) {
    new klass().bar()
}

x(class {
    bar() {
        console.log(2)
    }
})

Sign up to request clarification or add additional context in comments.

Comments

0

This is defining an anonymous class (in Java terminology... not sure if that is the correct name for JS). This example is pretty nonsensical. I could see it being used if the function f was accepting a class definition and then instantiated an object using it and proceeded to call methods on the object and perhaps return it. So it could be used in a general factory function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.