Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

set setTimeout callback's this to window object #2497

Merged
merged 1 commit into from
Jun 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions js/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { assert } from "./util";
import * as msg from "gen/cli/msg_generated";
import * as flatbuffers from "./flatbuffers";
import { sendAsync, sendSync } from "./dispatch";
import { window } from "./window";

interface Timer {
id: number;
Expand Down Expand Up @@ -186,8 +187,8 @@ function setTimer(
args: Args,
repeat: boolean
): number {
// If any `args` were provided (which is uncommon), bind them to the callback.
const callback: () => void = args.length === 0 ? cb : cb.bind(null, ...args);
// Bind `args` to the callback and bind `this` to window(global).
const callback: () => void = cb.bind(window, ...args);
// In the browser, the delay value must be coercible to an integer between 0
// and INT32_MAX. Any other value will cause the timer to fire immediately.
// We emulate this behavior.
Expand Down
12 changes: 12 additions & 0 deletions js/timers_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,15 @@ test(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise<
await waitForMs(1);
assertEquals(count, 1);
});

test(async function timeoutCallbackThis(): Promise<void> {
const { promise, resolve } = deferred();
const obj = {
foo(): void {
assertEquals(this, window);
resolve();
}
};
setTimeout(obj.foo, 1);
await promise;
});