js 盗用 this 方法

[size=large]原因,想写一些通用的函数,比如数组的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))
[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值