Wikipedia talk:User scripts/Guide: Difference between revisions

Content deleted Content added
User settings: update my comment
User settings: personally still recommend declaring a global variable explicitly
Line 63:
::I forgot that in the context of a browser, global variables declared with <code>var</code> are properties of the window object... That being said, now that the <code>let</code> keyword has been long available, it's highly preferable to use <code>let</code> to define globals, keeping the window object clear of non-standard properties. [[User:Isaacl|isaacl]] ([[User talk:Isaacl|talk]]) 23:21, 10 February 2021 (UTC)
:::I don't think <code>let</code> works at all in common.js. Replacing your common.js with <code>let test1 = true;</code> results in {{tq|VM5431:1 JavaScript parse error (scripts need to be valid ECMAScript 5): Parse error: Missing ; before statement in file 'User:Novem_Linguae/common.js' on line 1}}. I think this is what threw me off originally, causing me to give up and switch to <code>window.foo = 'bar';</code>. Now that I tested some more just now, <code>var foo = 'bar';</code> in common.js works, and a <code>try{}catch{}</code> block in the child file [https://en.wikipedia.org/wiki/User:Novem_Linguae/Scripts/VariableTest.js also works], as long as you use <code>var</code>. While that <code>try{}catch{}</code> block works, I still like <code>window.foo = 'bar';</code>, because the <code>try{}catch{}</code> block is [https://en.wikipedia.org/wiki/User:Novem_Linguae/Scripts/VariableTest.js very verbose]. –[[User:Novem Linguae|<span style="color:limegreen">'''Novem Linguae'''</span>]] <small>([[User talk:Novem Linguae|talk]])</small> 11:39, 11 February 2021 (UTC)
::::I see—the MediaWiki loader is parsing the script first and validating if it is valid ECMAScript 5. For a smoother transition to ECMAScript 6 one day, I'd still recommend declaring an explicit, uniquely-named global using <code>var</code>, storing individual settings as properties within it, and checking for its existence in code with something like this:<syntaxhighlight lang="javascript">var MySuperScriptPrefs = typeof MySuperScriptPrefs !== 'undefined' ? MySuperScriptPrefs :
{
// ... set default values ...
};</syntaxhighlight> [[User:Isaacl|isaacl]] ([[User talk:Isaacl|talk]]) 17:43, 11 February 2021 (UTC)