重写 window.alert 并传递多个参数
我试图覆盖 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');
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');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
for-in
迭代对象的所有可枚举属性,其中包括对象或其原型中定义的任何内容。大多数内置函数都被声明为不可枚举,因此它们在正常迭代期间不会出现。 ECMAScript 5 允许您将自己的属性定义为不可枚举的,尽管我不确定哪些浏览器支持此功能: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:正如 casablanca 所提到的,
for in
会迭代您定义的属性位于对象原型链中。要解决此问题,请使用
hasOwnProperty()
< /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()
.window.alert
是一个常量函数,您不能直接重新定义它:Javascript 覆盖警报
window.alert
is a constant function, you cannot redefine it directly:Javascript overriding alert