Why if we run the following javascript code:
var foo = {
bar: function () {
alert('s');
}
}
//1. foo.bar();
//2. var a = foo.bar;
//3. var b = (foo.bar);
(foo.bar)();
we'll get an error message "foo is undefined", but if we uncomment 1. or 2. or 3. line we'll get alert 's'? I know that it's about Reference type and GetValue(), but I don't really understand the point.
Thanks
It's because you don't have a semicolon before the (foo.bar).
This causes the (...) to be interpreted as a function call operator, so it's trying to invoke the previous expression as though it was a function.
var foo = {
bar: function () {
alert('s');
}
}(foo.bar) // <-- It sees it like this
If you terminate the previous with a ;, it'll work.
var foo = {
bar: function () {
alert('s');
}
}; // <--- right here
//1. foo.bar();
//2. var a = foo.bar;
//3. var b = (foo.bar);
(foo.bar)();
So the reason it worked when the other lines were uncommented is that they are terminated.
If you want to exclude semicolons (which is what I do), you'll generally be safe if you follow these rules:
( unless you have a ; before it[ unless you have a ; before itWhenever I start a line with one of those characters, I put a ; before it so I know the previous statement has been terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With