i’ve tried to do a very simple IIFE below,
<script type="text/javascript">
var obj = new Object;
(function(_obj) {_obj.prop = 'defined';})(obj);
if(typeof obj.prop === undefined)
alert('undefined');
else
alert(obj.prop);
</script>
Why does the script alert “undefined” than “defined” as a result?
@EDIT
The script shoud have worked as expected except:
- The unintended
typeof obj.prop === undefinedis wrong, butobj.prop === undefinedshould be used instead. -
When omitting parenthesis below, the script doesn’t work as expected but none of syntax error is raised from rhino.
function(_obj) {_obj.prop = 'defined';}(obj);
Your code alerts
'defined'but for the wrong reason.This…
should be this…
…because
typeofreturns a string representing the type of object.Don’t use the
typeofhack when testing forundefined. It’s confusing, and can be the source of bugs such as the one you encountered.If you’re that worried about
undefinedbeing redefined, then do this…