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

Commit e790163

Browse files
committed
perf($controller): cache the later constructor
1 parent 0bf0cc6 commit e790163

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
@@ -109,9 +109,13 @@ function $ControllerProvider() {
109109
// This feature is not intended for use by applications, and is thus not documented
110110
// publicly.
111111
// Object creation: http://jsperf.com/create-constructor/2
112-
var controllerPrototype = (isArray(expression) ?
113-
expression[expression.length - 1] : expression).prototype;
114-
instance = Object.create(controllerPrototype);
112+
constructor = isArray(expression) ? expression[expression.length - 1] : expression;
113+
var Constructor = constructor.$$Constructor;
114+
if (!Constructor) {
115+
Constructor = constructor.$$Constructor = function Constructor() {};
116+
Constructor.prototype = constructor.prototype;
117+
}
118+
instance = new Constructor();
115119

116120
if (identifier) {
117121
addIdentifier(locals, identifier, instance, constructor || expression.name);

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)