Reputation: 41597
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 than 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 :)
Upvotes: 0
Views: 1183
Reputation: 145002
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.
Upvotes: 0
Reputation:
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.
Upvotes: 3