zuroc 发表于 2013-1-27 04:51:40

js 盗用 this 方法

原因,想写一些通用的函数,比如数组的indexOf.

直接绑定到array的prototype很方便,但是有时候,我们不想这么做,更何况,对于array like object,调用起来也麻烦.

因此需要有一套函数,既可以绑定到array.prototype,也可以作为一种函数调用.

因此
_________________________________
function extend(f,o){
    function wrap(c){//这个wrap很重要 我第一次就是在这里犯错了
      return function(){
            return c.apply(this.__this||this,arguments)
      }
    }
    f=f.prototype;
    for(var i in o)if(!f)f=wrap(o);
}

function wrapper(f){
var f=function (o){
return new f.prototype.init(o)
}
f.prototype={
init:function(o){this.__this=o;return this}
}
f.prototype.init.prototype=f.prototype
return f;
}

$A=wrapper()
ArrayExtend={
remove:function(e){
    for(var i=this.length;i>=0;--i){
      if(this==e){
            this.splice(i,1)
      }
    }
    return this
}
}
extend($A,ArrayExtend)
extend(Array,ArrayExtend)

alert($A().remove(1))
alert(.remove(1))
页: [1]
查看完整版本: js 盗用 this 方法