切换上下文

来源:互联网 发布:资产阶级革命知乎 编辑:程序博客网 时间:2024/05/21 18:34


apply: 两个参数,第一个是上下文,第二个是参数组成的数组。

call:多个参数,第一个是上下文,后续是参数序列


切换上下文:

var proxy=function(func,thisObject){return (function(){   return func.apply(thisObject,arguments);});}
或者:

bind() //ECMAScript 5;

例:jQuery(element).click(this.click.bind(this));

兼容未实现浏览器:

if(!Function.prototype.bind){   Function.prototype.bind=function(obj){   var slice=[].slice,   args=slice.call(arguments,1),  self=this,  nop=function(){},  bound=function(){     return self.apply(this intanceof nop ? this:(obj || {}),args.concat(slice.cal(arguments)));  }  nop.prototype=self.prototype; bound.prototype=new nop(); return bound;}}

或使用jquery : $.proxy(func,thisObject);

原创粉丝点击