Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix($injector): instantiate returns instance, if non-object value ret…
Browse files Browse the repository at this point in the history
…urned from constructor
  • Loading branch information
vojtajina committed Feb 9, 2012
1 parent 3173d86 commit 7767392
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
11 changes: 7 additions & 4 deletions src/Injector.js
Original file line number Diff line number Diff line change
Expand Up @@ -429,12 +429,15 @@ function createInjector(modulesToLoad) {
}
}

function instantiate(Type, locals){
var Constructor = function(){},
instance;
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;

Constructor.prototype = Type.prototype;
instance = new Constructor();
return invoke(Type, instance, locals) || instance;
returnedValue = invoke(Type, instance, locals);

return isObject(returnedValue) ? returnedValue : instance;
}

return {
Expand Down
27 changes: 25 additions & 2 deletions test/InjectorSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,12 @@ describe('injector', function() {


it('should allow constructor to return different object', function() {
var t = $injector.instantiate(function() { return 'ABC'; });
expect(t).toBe('ABC');
var obj = {};
var Class = function() {
return obj;
};

expect($injector.instantiate(Class)).toBe(obj);
});


Expand All @@ -616,6 +620,25 @@ describe('injector', function() {
$injector.instantiate(function() { throw 'MyError'; });
}).toThrow('MyError');
});


it('should return instance if constructor returns non-object value', function() {
var A = function() {
return 10;
};

var B = function() {
return 'some-string';
};

var C = function() {
return undefined;
};

expect($injector.instantiate(A) instanceof A).toBe(true);
expect($injector.instantiate(B) instanceof B).toBe(true);
expect($injector.instantiate(C) instanceof C).toBe(true);
});
});

describe('protection modes', function() {
Expand Down

0 comments on commit 7767392

Please sign in to comment.