`

递归算法在javascript中使用的小技巧 (javascript的对象封装方法介绍)

 
阅读更多
<iframe align="top" marginwidth="0" marginheight="0" src="http://www.zealware.com/46860.html" frameborder="0" width="468" scrolling="no" height="60"></iframe>
By Ben


比如求 10! 的结果

有两种解法:
法一:
一般的做法:
//===========================
document.writeln("
递归算法一:
");
//===========================
function factorial(x) {
if(x return 1;
else
return x * factorial(x - 1);
}

document.writeln("10!=" + factorial(10));
法二:
还可在类的方法中执行递归,但这有点儿冒险。
在JavaScript中调用类的方法名来进行递归,会造成“Object Expected”错误。为避免这个错误,必须用方法的基本函数名或callee参数来执行递归。以清单D为基础,我在myMath类中添加了阶乘方法,如下所示。
document.writeln("
递归算法二:
");
function myMath() {
//=======================================
this.result; //Result of method

this.factorial = myFactorial; //Factorial method
function myFactorial(x) {
if(x return 1;
else {
this.result = x * arguments.callee(x - 1);
return this.result;
}
}
//=======================================
}
var math = new myMath(); // Create an instance
document.writeln("10! =" + math.factorial(10));


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=192304


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics