在javascript和Math对象中扩展Number.prototype? [英] Extending Number.prototype in javascript and the Math object?

查看:78
本文介绍了在javascript和Math对象中扩展Number.prototype?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么Javascript具有全局Math对象而不是给出数字自己的方法。它有充分的理由吗?

I've always wondered why Javascript has the global Math object instead of giving numbers their own methods. Is there a good reason for it?

这样的事情也有任何缺点(效率除外)吗?:

Also are there any drawbacks (other than efficiency) to doing something like this?:

Number.prototype.round = function(){
    return Math.round(this);
};

为了清楚起见,我明白像π这样的常量需要某个地方和函数应用于一个数字,如最小/最大。问题主要是关于只影响单个数字的方法,如圆形,abs,sin,pow等。

Just to make clear, I understand that constants like π need somewhere and functions that are applied on more than one number like min/max. The question was mainly concerning methods which only effect a single number such as round, abs, sin, pow, etc.

推荐答案

Math 对象的原因很简单:因为Java做到了。不是最好的理由,但我们在这里。我认为在道格拉斯·克罗克福德开始他的竞选活动以抑制一半语言*之前,事情变得更有意义了。最初你被允许或意味着做这样的事情:

The reason for the Math object is simple: "because Java does it". Not the best of reasons, but here we are. I guess things made more sense back then, before Douglas Crockford started his campaign to suppress half the language*. Originally you were "allowed", or meant, to do things like this:

with (Math) {
  var n = min( round(a) * round(b), sqrt(c) );
  var result = exp( n + d );
}

扩展 Number.prototype 是别人可能会做同样的事情。或者更糟糕的是,例如,将 Number.prototype.round 定义为对称舍入函数。

The drawback to extending Number.prototype is that someone else might do the same thing. Or worse, for example, define Number.prototype.round as a symmetrical rounding function.

如果您正在寻找让生活更轻松的方法,为什么还要停在那里?为什么不简单地将 Math 函数作为全局函数包含在内?

If you are looking for ways to make your life easier, why stop there? Why not simply include Math functions as global functions?

var m = 'abs acos asin atan atan2 ceil cos exp floor log max min ' +
        'pow random round sin sqrt tan PI').split(' ');
for (var i=0,l=m.length; i<l; i++) {
  window[ m[i] ] = Math[ m[i] ];
}

这会将所有数学函数放入全局范围,有效地允许您停止输入数学。问问自己:使用这些函数扩展 Number 和扩展窗口之间有什么真正的区别吗?

This will drop all the math functions into the global scope, effectively allowing you to stop typing "Math." Ask yourself: Is there any real difference between extending Number and extending window with these functions?

*在你激怒我之前:Crockford的评论不应该被认真对待。我同意他的观点, with 在隐含的全球环境中非常危险。

* Before you flame me: The Crockford comment is not meant to be taken too seriously. I do agree with him that with is very dangerous in an implicit global environment.

这篇关于在javascript和Math对象中扩展Number.prototype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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