$(function () { var input_type = { init:function ($obj) { this.name = $obj.html().split("") this.length = this.name.length; this.i = 0; }, pri:function () { var $this = this //在此處只能使用閉包,因為windown.settimeout使函數的this指向object windown,而非原型鏈的this對象。而此時我需要遞歸,所以只能將this對象傳到閉包內,遞歸匿名的閉包函數。 return (function () { if ($this.i > $this.length) { window.clearTimeout(Go) return false; } var char = $this.name $(".div1").append(char[$this.i]) $this.i++ var Go = window.setTimeout(arguments.callee, 100)//在這里arguments.callee妙用因為是匿名閉包,調用函數本身。 }) } } //建立class類 function Input_type() { this.init.apply(this, arguments) } Input_type.prototype = input_type //創建實例 var p = new Input_type($(".content")) p.pri()() });
總結:為了實現每次循環間隔時間,用window.settimeout遞歸的寫法。 因為想用原型鏈封裝,this沖突,所以遞歸調用匿名的閉包函數。用arguments.callee表示匿名函數。
demo: