如何在Javascript中的原型函数中编写递归函数?

时间:2014-10-29 09:30:44

标签: javascript numbers prototype

让我们说,我正在尝试为所有"数字添加功能"在javascript中有一个名为" factorial"的函数。所以,例如:

var num = 5
console.log( num.factorial() ) // should display 120

为了实现这一目标,这里有以下功能

Object.defineProperty(Number.prototype, "factorial", {
  enumerable: false,
  value: function() {
    if(this <= 1) return 1;
    return this * factorial(this - 1);
  }
})

显然,这将返回一个错误,说明函数&#34; factorial&#34;不存在。如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

Object.defineProperty(Number.prototype, "factorial", {
    enumerable: false,
    value: function() {
        if(this <= 1)
            return 1;
        return this * (this - 1).factorial();
    } //                   ^
});

正如您所提到的,factorial是您问题中未定义的函数,但 Number原型上的函数。
因此,您想要做的是在递归中对数字factorial调用this - 1

为了能够在this - 1上调用该函数,您可以将其包含在()括号中。