Skip to content

Commit a6cd945

Browse files
mrochzpao
authored andcommitted
Fix 'this' in static methods
binds static methods on the descriptor to the component's actual constructor, so that `foo.constructor.bar()` and `Foo.bar()` run with the same `this`.
1 parent 431155d commit a6cd945

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

src/core/ReactCompositeComponent.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,9 @@ function mixStaticSpecIntoComponent(ConvenienceConstructor, statics) {
549549
);
550550
result = createChainedFunction(existingProperty, property);
551551
}
552-
ConvenienceConstructor[name] = result;
552+
ConvenienceConstructor[name] = typeof result === 'function' ?
553+
result.bind(ConvenienceConstructor.type) :
554+
result;
553555
ConvenienceConstructor.type[name] = result;
554556
}
555557
}

src/core/__tests__/ReactCompositeComponent-test.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1201,7 +1201,10 @@ describe('ReactCompositeComponent', function() {
12011201
abc: 'def',
12021202
def: 0,
12031203
ghi: null,
1204-
jkl: 'mno'
1204+
jkl: 'mno',
1205+
pqr: function() {
1206+
return this;
1207+
}
12051208
},
12061209

12071210
render: function() {
@@ -1218,6 +1221,8 @@ describe('ReactCompositeComponent', function() {
12181221
expect(Component.ghi).toBe(null);
12191222
expect(instance.constructor.jkl).toBe('mno');
12201223
expect(Component.jkl).toBe('mno');
1224+
expect(instance.constructor.pqr()).toBe(Component.type);
1225+
expect(Component.pqr()).toBe(Component.type);
12211226
});
12221227

12231228
it('should support statics in mixins', function() {

0 commit comments

Comments
 (0)