D isn't the only language with janky closure semantics

JN 666total at wp.pl
Sat Aug 30 23:26:43 UTC 2025


On Friday, 29 August 2025 at 22:28:17 UTC, H. S. Teoh wrote:
> I happen to be working on some JS today (gasp!), and ran into 
> this odd
> behaviour.  Code snippet:
>
> ```js
> function buildDialog(label, buttons) {
> 	const dlg = document.createElementNS(...);
> 	...
> 	for (button of buttons) {
> 		const btnElem = document.createElementNS(...);
> 		...
> 		btnElem.addEventListener(click, (ev) => {
> 			button.action(ev); // <--- this was acting up
> 		});
> 	}
> }

In old javascript, before let/const came into JS the way to 
resolve this would be to use "Immediately Invoked Function 
Expression" 
https://developer.mozilla.org/en-US/docs/Glossary/IIFE to force a 
new scope

so like this:

```js
  (function( capturedBtn ){

       btnElem.addEventListener( 'click', (ev) => { 
capturedBtn.action(ev); } );
  })( button );

```


More information about the Digitalmars-d mailing list