user70192 user70192 - 1 month ago 7
Javascript Question

Implementing interfaces in JavaScript

I'm learning JavaScript. My background is traditionally in Java and C#. In those environments, I could use interfaces. A lot of times, I'd have a pattern that looked like this:

var implementers = GetForInterface<ISomeInterface>();

foreach (var implementer in implementers)
{
implementer.SomeMethod();
}


My question is, how do I do something similar in JavaScript? The main thing I can't seem to figure out is the
GetForInterface
part. I'm not sure what this design pattern is called.

Thank you

Answer

There is no Interfaces in Javascript,

The design pattern you are talking about is service locator, but usually this is not the way to go on javascript .

you could use some library to do this : service-locator or implement it your self with classes and inheritance .

a simple example to go is to hold an array of instances that inherit from the same class and you will be able to loop over them ( and activate the same method for all as desired )