skip to content
dz

Back to the article · Zurück zum Artikel (Deutsch)

Example 03: Property set before the upgrade

Rule 1: Don't touch attributes or children in the constructor

A property is set before the class is defined. It shadows the setter. Element B fixes that in the connectedCallback.

How to try it

  1. Open the console of the developer tools (F12, Cmd+Opt+I on a Mac). The "Console output" box on this page shows the same lines.
  2. On A the property stays on the element (own property: true), the setter never ran.
  3. On B you see setter called: early, and the property on the element is gone (own property: false).
Console output mirrored from console.log() and errors on this page, the same text as in the developer tools
Expected output what the lines above should say
setter called: early
A own property: true
B own property: false

Live example

Source

<x-a></x-a>
<x-b></x-b>

<script type="module">
	const a = document.querySelector('x-a');
	const b = document.querySelector('x-b');
	a.value = 'early';
	b.value = 'early';

	class XA extends HTMLElement {
		#v;
		get value() {
			return this.#v;
		}
		set value(v) {
			this.#v = v;
			console.log('setter called:', v);
		}
	}

	class XB extends XA {
		connectedCallback() {
			if (Object.hasOwn(this, 'value')) {
				const v = this.value;
				delete this.value;
				this.value = v;
			}
		}
	}

	customElements.define('x-a', XA);
	customElements.define('x-b', XB);

	console.log('A own property:', Object.hasOwn(a, 'value'));
	console.log('B own property:', Object.hasOwn(b, 'value'));
</script>