1

I am trying to override the window.alert to pass multiple parameters.

Please someone explain me why for/in inherits Array.prototype.tester's body into list?

Thank you very much.

Array.prototype.tester = function() {
    return 'tester';
}

window.alert = function() {
    var args = Array.prototype.slice.call(arguments);
    var list = [];

    for (var i in args) {
        list.push(args[i]);
    }

    return list.join(', '); // WHY???? alerts: "arg1, arg2, function () { return "tester"; }"
    //return args.join(', '); // alerts: "arg1, arg2" expected.
}

alert('arg1', 'arg2');
Nizzy
  • 1,879
  • 3
  • 21
  • 33

3 Answers3

2

for-in iterates over all enumerable properties of an object, which includes anything defined in the object or its prototypes. Most built-in functions are declared non-enumerable, so they don't appear during normal iteration. ECMAScript 5 allows you to define your own properties as non-enumerable, although I'm not sure which browsers support this:

function testerFunc() {
  return 'tester';
}

Object.defineProperty(Array.prototype, 'tester', {
  value: testerFunc,
  writable: true,
  enumerable: false,
  configurable: true
});
casablanca
  • 69,683
  • 7
  • 133
  • 150
0

window.alert is a constant function, you cannot redefine it directly:

Javascript overriding alert

Community
  • 1
  • 1
loentar
  • 5,111
  • 1
  • 24
  • 25
0

As mentioned by casablanca, for in iterates over properties defined by yourself that are in the objects prototype chain.

To fix this, use hasOwnProperty().

for (var i in args) {
    if (args.hasOwnProperty(i)) {
        list.push(args[i]);
    }
}
Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180