What does the underscore in '_$httpBackend_' mean?
When doing testing with AngularJS, you might have noticed code like this:
var backend;
inject(function(_$httpBackend_) {
backend = _$httpBackend_;
});
Where do the mysterious underscores come from? This is just a trick to make it possible to save injected objects in variables with their 'normal' name, like so:
var $httpBackend;
inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
});
The underscores are ignored by the injector function, so you can use this for any injectable object.
Written by Roger Braun
Related protips
3 Responses
That explanation makes no sense. It looks more like a way to make an argument name that looks a lot like an existing variable name. It is the human reader who can ignore the underscores. To javascript, $httpBackend
and _$httpBackend_
are as different as foo
and bar
.
Of course, this is just for the humans and $httpBackend
and _$httpBackend_
are different variables. But the injector function tries to figure out which service to inject based on the argument names. In this case, it ignores the underscores to make it possible to assign the inner scope _$httpBackend_
to the outer scope $httpBackend
and use it somewhere else.
Ah, that makes sense, thanks.