通过原型扩展Math对象不起作用 [英] Extending Math object through prototype doesn't work

查看:110
本文介绍了通过原型扩展Math对象不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试扩展JavaScript Math 。但有一件事让我感到惊讶。

I try to extend JavaScript Math. But one thing surprised me.

当我试图通过原型扩展它

Math.prototype.randomBetween = function (a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a);
};

在控制台中我有错误'无法设置属性'randomBetween'of undefined'...

In console I have error 'Cannot set property 'randomBetween' of undefined' ...

但如果我将此函数设置为 Math .__ proto __

But if I asigne this function to Math.__proto__

Math.__proto__.randomBetween = function (a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a);
};

然后一切正常。

可以有谁解释我为什么这样工作?我感谢任何帮助。

Can anybody explain me why it works in this way? I appreciate any help.

推荐答案

数学不是构造函数,所以它没有原型属性:

Math isn't a constructor, so it doesn't have prototype property:

new Math(); // TypeError: Math is not a constructor

相反,只需将方法添加到数学本身作为自有财产

Instead, just add your method to Math itself as an own property:

Math.randomBetween = function (a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a);
};

您使用 __ proto __ 的方法有效,因为,因为 Math 是一个对象实例, Math .__ proto __ Object.prototype

Your approach with __proto__ works because, since Math is an Object instance, Math.__proto__ is Object.prototype.

但请注意,您要添加 randomBetween 所有对象的方法,不仅是 Math 。这可能会有问题,例如在循环中使用迭代对象时。

But then note you are adding randomBetween method to all objects, not only to Math. This can be problematic, for example when iterating objects with a for...in loop.

这篇关于通过原型扩展Math对象不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆