Skip to content

Svelte 5: scope of class this changes in handlers depending on how class methods are attached #10001

@arxpoetica

Description

@arxpoetica

Describe the bug

The scope of this changes when attaching class method handlers differently to on*.

That is,

<button onclick={() => counter.increment()}>

vs

<button onclick={counter.increment}>

Reproduction

Open the console with both examples to see the output.

Working Example (1)

Attaching and calling from an arrow function.

<button onclick={() => counter.increment()}>

Outputs the Counter {#count: {...}} class instance.

Broken (?) Example (2)

Attaching directly as class method.

<button onclick={counter.increment}>

Clicking the button produces the scope of the <button> element.

image

This breaks reactivity, so this.count = this.count + 1 is happening on the <button> element instead of the class instance.

Logs

Logs are listed above under <<Reproduction>>.

System Info

n/a -- running on https://svelte-5-preview.vercel.app/ version `5.0.0-next.26`

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions