如何使我自己的JavaScript数学方法工作?

时间:2014-11-21 10:54:25

标签: javascript math methods

在javascript中创建此函数时,它可以实现预期目标:

Number.prototype.powown = function(b) {
    return Math.pow(this, b);
}
var a = 3;
var b = 6;
document.write(a.powown(b));

但是我想让它在不使用变量的情况下工作,我无法弄清楚它是如何工作的。

当我提供此代码时,我想让它工作:

  

文件撰写(Math.powown(3,6));

2 个答案:

答案 0 :(得分:0)

由于Math对象已经有Math.pow(),您可以直接使用它,如果您想添加自定义函数,可以将自定义函数添加到Math对象,例如:

Math.powown = function() {
  return Math.pow(arguments[0], arguments[1]);
};
console.log(Math.powown(2,2)); //gives 4

答案 1 :(得分:0)

我认为你要做的就是这个

Number.prototype.pow = function(a){ return Math.pow(this, a); }

所以你可以这样称呼它

(10).pow(5);

或者

10..pow(5);

注意:的 你无法调用10.pow(5)括号或。 javascript需要知道10是数字

加成: 如果你想变得非常愚蠢,你可以将Math的所有方法应用到像这样的数字原型。

Object.getOwnPropertyNames(Math).forEach(function(p){
    Number.prototype[p] = function(){
        return Math[p].apply(null, Array.prototype.concat.apply([this], arguments));
    }
});