Skip to content

Cannot directly @attach a class function #16153

@Refzlund

Description

@Refzlund

Describe the bug

When using a class function as an attachment, it loses its this reference.

Reproduction

Svelte Playground

<script>
	
	class Example {
		element
		setElement(element) {
			this.element = element
		}
	}

	const example = new Example()
	
	let name = 'world';
	
</script>

<!-- Does not work - loses `this` reference -->
<div {@attach example.setElement} style:color='tomato'>
	Does not work - loses `this` reference
</div>

<!-- Works -->
<div {@attach el => example.setElement(el)} style:color='lightgreen'>
	Works
</div>

Logs

TypeError: Cannot set properties of undefined (setting 'element')
    at setElement (playground:output:2786:18)
    at eval (playground:output:2527:63)
    at update_reaction (playground:output:1478:57)
    at update_effect (playground:output:1645:19)
    at flush_queued_effects (playground:output:1753:6)
    at flush_queued_root_effects (playground:output:1725:6)

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
    Memory: 5.14 GB / 31.93 GB
  Binaries:
    Node: 23.11.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.9.2 - C:\Program Files\nodejs\npm.CMD
    bun: 1.2.16 - ~\.bun\bin\bun.EXE
  Browsers:
    Edge: Chromium (132.0.2957.115)
  npmPackages:
    svelte: ^5.34.1 => 5.34.1

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