views:

43

answers:

3

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');
A: 

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

http://stackoverflow.com/questions/1729501/javascript-overriding-alert

loentar
This link says you can.
Fabien Ménager
+2  A: 

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
A: 

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]);
    }
}
Matt