js中的call和apply

来源:互联网 发布:windows不能访问samba 编辑:程序博客网 时间:2024/06/06 00:12

最近在看jQuery源码,里面好多地方用到了call(),apply()一直不是很理解这两个函数,今天花了点时间了解了一下,只是了解了一些皮毛


apply和call()的区别就是里面的参数

apply(thisObj,[arguments])

call(thisObj,arr1,arr2...)

根据网上说的,这两个函数的实质就是改版this的指向,例

 function add(a, b){console.info(this);this.a=a;this.b=b;alert(this.a);}function sub(a, b){console.info(this);this.a=a;this.b=b;alert(this.a);}add.call(sub, 'sub', 2);//提示subsub.apply(add, ['add', 2]);//提示add

thisObj也可以是一个对象,比如

</pre></p><p><pre name="code" class="javascript">function test(name){this.name=name;}test.prototype.sayName=function(){alert(this.name);}var t=new test('ttt');t.sayName();var a={'name':'tom'};t.sayName.call(a);//提示tom


好吧,组织不好语言,了解的也不多,第一篇文章就这样吧!继续努力!!!





0 0
原创粉丝点击