Ben Aston
Ben Aston

Reputation: 55759

Idiomatic Javascript dependency graph

Given the following Javascript, would it be better/more idiomatic to inject the MyService object into myMethod so that a fake version of MyService could be injected for testing? Or am I missing something?

var myObject = {
  myMethod: function() {
    var myService = new MyService();
    return myService.doSomething();
  }
}

Upvotes: 1

Views: 364

Answers (1)

Milad Naseri
Milad Naseri

Reputation: 4118

Dependency injection always takes precedence over hard-coding the dependencies. Also, by coding to interfaces (assuming the myObject instance has been given a copy of a Service object that has a doSomething() method) could come handy here.

Upvotes: 1

Related Questions