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 🙂
No. Prototyped methods go on object constructors. The default value of
var fooisundefined, which does not have a constructor.You can add the method to all objects by extending
Object.prototype.Now any value that has an object wrapper can use the method.
Notice that I used
Object.definePropertyfor 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
undefinedvalue in lieu of atypeoftest, consider the fact thattypeofis never needed for to test forundefined.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……as long as you heed the following…
Never shadow or define
window.undefinedwith a different valueNever 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.