Reputation: 5453
How can I manipulate the prototype
of a predefined object (for example an Array
) so that it does something when creating instances of that object?
Simply I want to alert('an array was created!')
whenever an Array is instantiated.
Upvotes: 0
Views: 141
Reputation: 337
I would suggest the you just create an array namespace for it:
array = {};
array.create = function() {
alert("Created an array");
return [];
}
So whenever you create an array you use: array.create(); .
You should not, and in this case can not, change native functionality. You have to be in charge of every array creation.
Upvotes: 1
Reputation: 179256
You can set a new method on an array by adding it to the Array.prototype
object:
Array.prototype.fizz = function () {
alert('works');
};
var arr = [];
arr.fizz();
However, this only allows you to create new methods, this does not allow you to extend existing methods*, nor does it allow you to override the Array
constructor.
Be careful adding new methods to existing types. This can adversely affect the entire scripting environment, and cause unexpected behavior in some libraries. Although some might call it "bad practice", it's quite common to use polyfills for cross-browser compatibility, such as by creating Array.prototype.indexOf
.
There is no such thing as a "newed" array, the word is "instantiated":
var a1, a2;
a1 = []; //a1 was instantiated with a new Array
a2 = new Array(); //a2 was also instantiated with a new Array
There is no cross-browser means of overriding the Array
constructor.
* it's possible to wrap an existing method in a function so that, when called, the existing method performs its original functionality, in addition to the new functionality. Although this might be referred to as extending an existing method, it is in fact creating a new method.
Upvotes: 3
Reputation: 227310
You can try to override Array
with your own function. It seems to work when doing new Array
, but not when doing []
.
(function() {
var _ac = Array;
Array = function() {
alert('an array was newed!');
return _ac.apply(this, arguments);
};
}());
DEMO: http://jsfiddle.net/DAg9A/
Upvotes: 2