It is trivial to add prototypes to all Function
s:
Function.prototype.foo = function () { return 'bar'; };
(new Function).foo(); // 'bar'
However, it is also bad practice to assign things to a global object's prototype, due to cross-module object reliance concerns, partially leading to the demise to earlier versions of prototype.js.
Suppose I want all of my functions to have the method foo
. I would do something similar to this:
(function () {
var Fn = Function;
Fn.prototype.foo = function () { return 'bar'; };
(new Fn).foo(); // 'bar'
}());
(new Function).foo() // also 'bar'. this is bad!
Unfortunately, this affects Function
's prototype as well, because Function was scoped by reference.
The usual "copy value" approach for passing primitive values into IIFEs would also fail, because Function
itself is an object.
(function (Fn) {
Fn.prototype.foo = function () { return 'bar'; };
(new Fn).foo(); // 'bar'
}(Function));
Function.foo // function () { return 'bar'; }
Given these examples, is it true that it is impossible to extend selected functions' prototypes, without affecting all other functions outside my scope?