`
zuroc
  • 浏览: 1292231 次
  • 性别: Icon_minigender_1
  • 来自: 江苏
社区版块
存档分类
最新评论

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[i])f[i]=wrap(o[i]);
}

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[i]==e){
            this.splice(i,1)
        }
    }
    return this
}
}
extend($A,ArrayExtend)
extend(Array,ArrayExtend)

alert($A([1,2,5]).remove(1))
alert([1,2,5].remove(1))
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics