views:

59

answers:

2

Javascript compiles this code without error:

function test() {
    property: true;
    alert('testing');
}
test(); // Shows message 'testing'
alert(test.property); // Shows 'undefined'

Is the content of property accessible in any way?

If not, what is the purpose of accepting this code?

+3  A: 

property is not a property here. It's a label-- something you could use with break or continue. You could reformat the code you have like this:

function test() {
    property: 
        true;
        alert('testing');
}

You're not actually referencing the label, and the thing that comes after it (true) is just a no-op statement, so nothing happens when it executes. The function only meaningfully contains an alert statement.


You seem to be confusing an object literal with a function definition. You could create an object with properties like this:

var test = {
    property: true;
};

You might also be confusing it with a couple other patterns. Let us know what you're trying to accomplish for more info.

quixoto
i guess Carlos is looking at someone else's code..
mykhal
Right, I have used it as a label. I was not trying to accomplish anything specific here, I just noticed that is valid syntax and thought there might be a new trick here. Thanks.
Carlos Gil
@mykhal why would you think that?
Carlos Gil
A: 
 test = function() {
    this.property = true;
    alert('testing');
}
var test = new test(); // Shows message 'testing'
alert(test.property); // Shows 'true'

'this' refers in this case to the function it is inside.

this.property = true;

You have to assign an instantiated function to a variable in order to use it:

var test = new test();
Michael Robinson