Search code examples
javascriptjquerymediawiki-api

Are Arrow syntax and function syntax really the same? (Cannot read property 'createDocumentFragment' of undefined)


So I have a really interesting thing happening with my code. When using arrow syntax to declare my function I get an error. But no error when I use the old function() syntax.

const clean = (blurb) => {
    blurb.find('a').each(()=> { $(this).replaceWith($(this).html()) });
}

(Cannot read property 'createDocumentFragment' of undefined)

^^^^Error^^^^

Versus

const clean = (blurb) => {
    blurb.find('a').each(function() { $(this).replaceWith($(this).html()) });
}

^^^^No Error^^^^

So clean should just remove all instances of the 'a' tag but this only works when I use the old method? Any idea as to why this is happening?

Thanks


Solution

  • Arrow functions do not have their own this, as regular functions do, which is probably the cause of your error.

    More information:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions