3

I am a beginner in angularjs, I start learning by their tutorial, but when comes to dependency injection, I am not quite understand what it means

function SomeClass(greeter) {
  this.greeter = greeter;
}

SomeClass.prototype.doSomething = function(name) {
  this.greeter.greet(name);
}

In the above example SomeClass is not concerned with creating or locating the greeter dependency, it is simply handed the greeter when it is instantiated.

This is desirable, but it puts the responsibility of getting hold of the dependency on the code that constructs SomeClass.

What actually does the bolded sentence mean?

"The code that construct SomeClass", does that mean the function SomeClass(greeter)?

Thanks all for the advice

user2499325
  • 419
  • 1
  • 5
  • 15
  • 3
    I think it means `var some = new SomeClass(greeterInstance)`. So the responsibility of this code is to provide proper `greeterInstance` object implementing `greeter` interface. – dfsq Jul 15 '14 at 05:41
  • 1
    @dfsq explanation is totally right. The other way around: If your `greeterInstance` doesn't match the greeter interface (e.g. a greet method) `some.doSomething()` will throw an error. This tightly coupling is what DI solves. – Zhonk Jul 15 '14 at 05:47
  • Check this : http://stackoverflow.com/questions/23494233/need-to-understand-dependency-injection-in-angular-js – Siddharth_Vyas Jul 15 '14 at 05:49
  • @dfsq Totally understood, thanks for the brilliant explanation! Nice and clear – user2499325 Jul 15 '14 at 06:07

1 Answers1

1

No, function SomeClass(greeter) is a constructor function.

The code that constructs SomeClass is in this context whatever code does (something along the lines of)

var greeter = new Greeter();
var someInstance = new SomeClass(greeter);

This is typically somewhere in the DI framework code.

The bottom part is just (one of several) ways of declaring a member-function on a class in Javascript.

SomeClass.prototype.doSomething = function(name) {
  this.greeter.greet(name);
}

All that does is make sure that every instance of SomeClass has a doSomething function. For the purpose of explaining DI that part is completely irrelevant.

ivarni
  • 17,658
  • 17
  • 76
  • 92