No. Prototyped methods go on object constructors. The default value of var foo
is undefined
, which does not have a constructor.
You can add the method to all objects by extending Object.prototype
.
Object.defineProperty(Object.prototype, 'doTheFoo', {
value: function() { alert('foo'); }
});
Now any value that has an object wrapper can use the method.
Notice that I used Object.defineProperty
for the assignment. This is only available in ES5 compliant implementations. It makes the property non-enumerable, so it is relatively safe.
Since you seem to want this to work on an undefined
value in lieu of a typeof
test, consider the fact that typeof
is never needed for to test for undefined
.
If this is what you've been told, you've been deceived. Many people think this, merely because that's what they've always been told. It is not true.
The following test is a perfectly safe test for undefined
...
if (foo === undefined) {
...as long as you heed the following...
Never shadow or define window.undefined
with a different value
Never use any code that violates the #1
Never try to get the value of an undeclared variable
Be responsible to maintain an uncorrupted environment (a very simple task), and you'll have no issues.