There is no way to intercept direct property accesses in JavaScript. When a property is retrieved that hasn't been set than the result will be undefined
. Although null
and undefined
are usually considered to be the same thing they are in fact different entities.
In JavaScript undefined
means no value and null
means a value of null. In some cases you can mix undefined and null. For example, when using the ==
operator they are equivalent ((null == undefined) === true
). Using the non-coercing operator, ===
, they are different ((null === undefined) === false
).
You can use this to your advantage. While most people will claim that you should use the non-coercing equality operator (===
) it's mostly safe to put null
and undefined
in the same bucket, in less of course you actually care about the difference between the two. Where it gets tricky is that undefined
is a property of the global object and can therefore be assigned a new value.
If someone were to say undefined = 'donkey'
then null == undefined
would start to return false
. In practice this is almost never a problem since most people aren't foolish enough to reassign the value of undefined.
So, in a roundabout sort of way, you don't need to trap property accesses to return null
for properties that have not been set so long as you compare the result against null
using ==
.