I’m trying to define a function for the NodeList object. This is the code:
if (!NodeList.prototype.filter){
NodeList.prototype.filter = function(fun /*, thisp*/){
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this){
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
This works in Chrome, but not in Firefox. Firebug says “current_node.childNodes.filter is not a function” when I call the function:
nodes = current_node.childNodes.filter(filterByClass);
The weird thing is that this code:
if(typeof NodeList.prototype.filter == 'function')
alert(NodeList.prototype.filter);
displays the function’s code in both browsers.
It’s being used in a HTML, and it’s being included like this:
<script type="text/javascript" src="textselection.js"></script>
EDIT:
The Firefox version is 10.0.2 and the S.O. Ubuntu 11.04
EDIT2:
I had forgotten one important factor… it’s being used whithin an iframe
Changes made to an object’s prototype in one frame are not reflected in other frames. You’ll need to include your script in every frame where you want to extend
NodeList.prototype.Remember that
NodeList === window.NodeListand, in a frame,window !== top. So, in a frame,window.NodeList !== top.NodeList.Interestingly, for instantiable objects, like
Date, you can still take advantage of the prototype, provided you instantiate the object by first referencing the frame with the extended prototype. For example, if your parent frame extendedDateto have a.format()method, you could do something like this from a child frame: