Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Set Property ... of undefined --- bizarre

I'm getting a bizarre error in Chrome... check out the screenshot below.

I define record using object literal syntax.

I try setting the "id" property and get the exception.

I've tried both :

record['id'] = 'wtf';

and also

record.id = 'wtf';

I use this type of syntax all over the place in my script.... what could be going on here ? Is this a bug in Chrome ?

alt text

EDIT : I've solved the problem for now, but I'm still not sure why this is happening. I moved the definition of record to occur outside of the if block. Anyone know what could be occurring ? I thought all variable declarations were scoped to the function and therefore this shouldn't be an issue.

like image 675
rvandervort Avatar asked Nov 16 '10 18:11

rvandervort


1 Answers

The problem is most likely that dl is less than or equal to zero, so the statement that initializes record doesn't get executed. From your indentation, it looks like you intended for both statements to be part of the if block, but with no braces, the record['id'] = 'wtf'; statement gets executed no matter what.

By moving the variable initialization outside the if statement, you forced it to happen in any case and moved the assignment inside the if block (which, I'm assuming is what you wanted).

Probably a better way to solve it is adding braces like this:

if (dl > 0) {
    var record = {};

    record.id = 'wtf';
}

Unless you really do want to initialize record in both cases.

You are correct about variable declarations being scoped to the function, but the assignment doesn't happen until you get to that point in the code. record was in scope, but it still had its default value of undefined because you hadn't assigned anything to it yet.

like image 131
Matthew Crumley Avatar answered Sep 24 '22 08:09

Matthew Crumley