问题
var foo = {};
document.body.innerHTML = console.log = location.hash = 'Hi ' + '<br> ' + foo.bar + '<br> ' + foo.baz;
setTimeout(function()
{
foo.baz = foo["bar"] = [];
foo.bar.push(new Date);
foo.baz.push(new Date);
document.body.innerHTML = console.log = location.hash = 'Hi ' + '<br> ' + foo.bar + '<br> ' + foo.baz},
5000);
回答1:
Since you set node.bar
equal to false
, (node.foo && node.bar)
will evaluate to false
whether the properties are attached or not. Rather than checking if those properties are true
, you should check whether they are undefined:
if (typeof node.foo !== 'undefined' && typeof node.bar !== 'undefined')
{
...
}
else
{
...
}
回答2:
Looks like it may be implementation dependent:
The object that may be created in step 1 is not accessible outside of the above method. An implementation might choose to avoid the actual creation of the object. The only situation where such an actual property access that uses this internal method can have visible effect is when it invokes an accessor function.
So instead of accessing the property, stringify and pass by value.
References
- ECMAScript-5: Section 8.7.2 Note
来源:https://stackoverflow.com/questions/16246954/does-javascript-hoist-if-statements-when-object-literals-are-involved