If I create a trivial labeled statement such as:
foo: do { alert('hi') } while (false)
Is there any way to clone foo?
No, apparently this is not possible. Labels cannot be used in an assignment statement and the scope of a label is the conditional block of the loop in which it is defined.
pastureLoop:
for (i = 0; i < pastureLen; i++)
{
var pasture = pastures[i];
var cows = pasture.getCows();
var j, numCows = cows.length;
for (j = 0; j < numCows; j++)
{
var cow = cows[j];
if (cow.isSick())
{ break pastureLoop; }
healthyCows++;
}
}
pastureLoop:
for (i = 0; i < pastureLen; i++)
{
var pasture = pastures[i];
var cows = pasture.getCows();
var j, numCows = cows.length;
for (j = 0; j < numCows; j++)
{
var cow = cows[j];
if (cow.isEating())
{ continue pastureLoop; }
}
// No cows were eating, so fire the callback for pasture[i]
pasture.executeCallback(); // or whatever
}
The closest alternative is a labelled function declaration in non-strict mode:
B.3.2 Labelled Function Declarations
Prior to ECMAScript 2015, the specification of
LabelledStatement
did not allow for the association of a statement label with aFunctionDeclaration
. However, a labelledFunctionDeclaration
was an allowable extension for non-strict code and most browser-hosted ECMAScript implementations supported that extension. In ECMAScript 2015, the grammar productions forLabelledStatement
permits use ofFunctionDeclaration
as aLabelledItem
but 13.13.1 includes an Early Error rule that produces a Syntax Error if that occurs. For web browser compatibility, that rule is modified with the addition of the underlined text:LabelledItem : FunctionDeclaration
It is a Syntax Error if any strict mode source code matches this rule.
This can be used to create a declaration which is inaccessible:
function show_alert()
{
label:
{
break label;
var foo = 1;
}
console.log(foo);
}
but can be made accessible through string manipulation and the function constructor.
References