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

4
  • 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. Commented Jul 15, 2014 at 5: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. Commented Jul 15, 2014 at 5:47
  • Check this : stackoverflow.com/questions/23494233/… Commented Jul 15, 2014 at 5:49
  • @dfsq Totally understood, thanks for the brilliant explanation! Nice and clear Commented Jul 15, 2014 at 6:07

1 Answer 1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.