From e08f6f0ede03d09e71e44de5e524abd9789971d8 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=E9=BE=99=E8=85=BE=E9=81=93?= Date: Thu, 7 May 2020 01:41:34 +0800 Subject: [PATCH] fix(reactivity): use correct thisArg for collection method callbacks (#1132) --- .../reactivity/__tests__/collections/Set.spec.ts | 14 ++++++++++++++ packages/reactivity/src/collectionHandlers.ts | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/reactivity/__tests__/collections/Set.spec.ts b/packages/reactivity/__tests__/collections/Set.spec.ts index bf26e807dd..cdccd34799 100644 --- a/packages/reactivity/__tests__/collections/Set.spec.ts +++ b/packages/reactivity/__tests__/collections/Set.spec.ts @@ -412,5 +412,19 @@ describe('reactivity/collections', () => { `Reactive Set contains both the raw and reactive` ).toHaveBeenWarned() }) + + it('thisArg', () => { + const raw = new Set([ 'value' ]) + const proxy = reactive(raw) + const thisArg = {} + let count = 0 + proxy.forEach(function (this :{}, value, _, set) { + ++count + expect(this).toBe(thisArg) + expect(value).toBe('value') + expect(set).toBe(proxy) + }, thisArg) + expect(count).toBe(1) + }) }) }) diff --git a/packages/reactivity/src/collectionHandlers.ts b/packages/reactivity/src/collectionHandlers.ts index b03cbd589a..5aff152e93 100644 --- a/packages/reactivity/src/collectionHandlers.ts +++ b/packages/reactivity/src/collectionHandlers.ts @@ -146,9 +146,9 @@ function createForEach(isReadonly: boolean) { // 1. invoked with the reactive map as `this` and 3rd arg // 2. the value received should be a corresponding reactive/readonly. function wrappedCallback(value: unknown, key: unknown) { - return callback.call(observed, wrap(value), wrap(key), observed) + return callback.call(thisArg, wrap(value), wrap(key), observed) } - return getProto(target).forEach.call(target, wrappedCallback, thisArg) + return getProto(target).forEach.call(target, wrappedCallback) } } -- 2.47.2