JavaScript prototype to empty variable

Problem

Using JavaScript, is it possible to use prototype to add a method to a variable that hasn't been given a value yet.

For example, I can do this:

var foo = "bar";

String.prototype.doTheFoo = function(){
  console.log("foo is better then you");
};

foo.doTheFoo();

This gives all strings the method doTheFoo();

Is it possible to some how do the same, however with something that hasn't been given a value?

var foo;

(????).prototype.doTheFoo = function()...

Thanks :)

Problem courtesy of: Menztrual

Solution

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...

  1. Never shadow or define window.undefined with a different value

  2. Never use any code that violates the #1

  3. 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.

Solution courtesy of: user1106925

Discussion

Can you put gas in a car you don't have yet? Of course not; you can't attach something to nothing.

Likewise, you can't attach a method to an empty variable; there's nothing (and therefore no prototype to attach to).

Technically speaking, a declared but unassigned variable is undefined, which is a special primitive value type. Primitives have no properties, so you can't attach any methods to it.

You could add something to Object's prototype (from which everything else inherits), so that when you do assign some value to a variable, it will have that method, but this is a very, very bad idea.

Discussion courtesy of: josh3736

This recipe can be found in it's original form on Stack Over Flow.