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

Commit 1a45b60

Browse files
committed
perf($controller): cache the later constructor
1 parent 6e516a2 commit 1a45b60

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

src/ng/controller.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,13 @@ function $ControllerProvider() {
104104
//
105105
// This feature is not intended for use by applications, and is thus not documented
106106
// publicly.
107-
var Constructor = function() {};
108-
Constructor.prototype = (isArray(expression) ?
109-
expression[expression.length - 1] : expression).prototype;
107+
// http://jsperf.com/create-constructor/2
108+
constructor = isArray(expression) ? expression[expression.length - 1] : expression;
109+
var Constructor = constructor.$$Constructor;
110+
if (!Constructor) {
111+
Constructor = constructor.$$Constructor = function Constructor() {};
112+
Constructor.prototype = constructor.prototype;
113+
}
110114
instance = new Constructor();
111115

112116
if (identifier) {

test/ng/controllerSpec.js

+34
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,38 @@ describe('$controller', function() {
157157

158158
});
159159
});
160+
161+
describe('ctrl later', function() {
162+
it('should return a delayed constructor instance', function() {
163+
function Ctrl() {
164+
this.prop = 123;
165+
}
166+
Ctrl.prop = 123;
167+
Ctrl.prototype.foobar = Ctrl.foobar = function() { return this.prop; };
168+
169+
var setup = $controller(Ctrl, {}, true);
170+
var instance = setup.instance;
171+
172+
expect(Object.getPrototypeOf(instance)).toBe(Ctrl.prototype);
173+
expect(instance.foobar()).not.toBeDefined();
174+
175+
setup();
176+
expect(instance.foobar()).toBe(123);
177+
instance.prop = 456;
178+
expect(instance.foobar()).toBe(456);
179+
});
180+
181+
it('should work with inherited constructors', function() {
182+
function Parent() {}
183+
function Child() {}
184+
Child.prototype = new Parent();
185+
186+
var parent = $controller(Parent, {}, true).instance;
187+
var parent2 = $controller(Parent, {}, true).instance;
188+
var child = $controller(Child, {}, true).instance;
189+
190+
expect(parent.constructor).toBe(parent2.constructor, "should reuse the base controller");
191+
expect(Object.getPrototypeOf(child)).toBe(Child.prototype);
192+
});
193+
});
160194
});

0 commit comments

Comments
 (0)