I would expect the output of the following code to be:
one
two
three
Here’s the code: http://jsfiddle.net/5banB/15/
Why is the function code also in the output and how do I solve it?
And please don’t answer: loop only 3 times 🙂
Code from jsfiddle:
Object.prototype.example = function(args) {
var elmnt = this;
for(var a in args)
{
elmnt.innerHTML += args[a] + "<br/>";
}
}
var numbers = ['one', 'two', 'three'];
document.getElementById("mydiv").example(numbers);
Output
one
two
three
function (args) { var elmnt = this; for(var a in args) { elmnt.innerHTML += args[a] + "
"; } }
Update:
So how would I go about writing an extension of, say every node in my DOM? What’s the preferred way?
A
for inloop loops over all the enumerable properties on an object.You’ve added an
exampleproperty to every object.The Object constructor is on the prototype chain of the Array constructor so every array will have an
exampleproperty.Generally speaking, if you are using a
for inloop, you’ll want to usehasOwnPropertyto test that the property is directly on the object and not inherited through the prototype chain.