我正在尝试覆盖 window.alert 以传递多个参数。
请有人解释一下为什么 for/in 将 Array.prototype.tester 的主体继承到列表中?
非常感谢。
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');
最佳答案
for-in
遍历对象的所有可枚举属性,包括对象或其原型中定义的任何内容。大多数内置函数都声明为不可枚举的,因此它们不会在正常迭代期间出现。 ECMAScript 5 允许您将自己的属性定义为不可枚举的,尽管我不确定哪些浏览器支持这一点:
function testerFunc() {
return 'tester';
}
Object.defineProperty(Array.prototype, 'tester', {
value: testerFunc,
writable: true,
enumerable: false,
configurable: true
});
关于javascript - 覆盖 window.alert 并传递多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3287423/