1

Im using this function to generate a random string

function makeid(size)
    {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for( var i=0; i < size; i++ )
            text += possible.charAt(Math.floor(Math.random() * possible.length));

        return text;
    }

I try to create an array with two times the same random value like:

        var game = {
            _id:makeid(24),
            createdOn:new Date(),
            id : _id
        }

However the error shows _id is not defined. when I remove id:_id it is valid. Why is _id not defined at this moment, the decleration is above id:_id in the same scope right?

0

1 Answer 1

2

You cannot initialize the (game.)id to be equal to (game.)_id, first off you not referencing the object you just created so it would be looking for an variable _id which doesnt exist. Secondly, the object hasn't been instantiated yet so you can't reference that variable in the first place, you can do this though:

var _id = makeid(24);
var game = {
    createdOn:new Date(),
    id : _id
}
Sign up to request clarification or add additional context in comments.

5 Comments

Basically the same answer here, with a jsFiddle for you to play with: jsfiddle.net/tz746xdz
@johnny5 is it in anyway possible to access the variable in the array decleration?
@SvenB to access a variable in an object during its instanciation is not possible that I know of. You would have to access it either after you created it, or you would have to store it in a separate variable as shown above. Why does it have to happen during creation
@johnny5 im just trying some code, im used to programming c++ mostly but am trying some angular. I like to understand how the declerations etc work.
Okay Cool, well if anything they're simialar operation to Anonymous Types in C#, You can directly assign variables, but cannot access that object until after instanciation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.