编程小贴士

给你的编程提供小点子


js中Function的apply方法与call方法理解

最近在使用jQuery的$.each方法时很多,突然想到$.each($(‘div’),function(index,entity){});中的这个index和entity是哪冒出来的,而且可有可无的,而且这么高大上的能告诉我们当前遍历的下标和实例。所以看了一下jQuery源代码,是这么写的:

untitled.png

调试的时候走的是标红的这段代码,然后用到了callback.call这个函数,于是翻看了一下《js高级程序设计》,其中有比较深的解释。

首先,function是一个指向Function对象,函数名是一个指向函数的指针。那么在函数体内,就会有一个作用域,即this关键字。

this关键字指的是函数运行的作用域,举个例子来说,

  1. <script type=”text/javascript”>
  2.         function funcA() {
  3.             alert(this);
  4.             alert(“Function A”);
  5.         }
  6. </script>

上面这段代码中的函数funcA定义在全局环境中,那么函数体内的this即window对象。

下面该到call和apply的说明了。以call函数为例,call的第一个参数,就是改变函数的作用域,后面的参数为传入函数的所需的参数,必须与原函数的参数一直,举例说明:

  1. <script type=”text/javascript”>
  2.         var testO = { name: “Lily” };
  3.         function funcA(a,b) {
  4.             alert(this);
  5.             alert(“Function A”);
  6.         }
  7.         function funcB(a, b) {
  8.             funcA.call(testO, a, b);
  9.         }
  10.         funcB(1,2);  //this变成了testO
  11.     </script>

我们定义funcB函数的中,调用了funcA的call函数,这个时候我们改变了 funcA中this的指向,原本指向window的,现在指向了call的第一个参数testO这个对象。而且调用call时,因为funcA函数有两 个参数,所以如果要想funcA传递参数,必须一一指出参数,即后面的两个参数a和b,或者可以只穿第一个参数

即:funcA.call(testO);或者只传a,即:funcA.call(testO,a);

而apply与call的区别仅在于,apply的第二个参数可以是数组形式,而且不必一一指出参数,funcA.apply(testO,[a,b])

介绍完call与apply的基本用法,该说说他哥俩真正的用武之地了,扩充函数赖以运行的作用域。

  1. <script type=”text/javascript”>
  2.         window.color = “透明”;
  3.         var testObj = { color: “红色” };
  4.         function testFuc() {
  5.             alert(this.color);
  6.         }
  7.         $(function () {
  8.             1.testFuc(); //弹出“透明”
  9.             2.testFuc(this); //弹出“undefined”
  10.             3.testFuc.call(this.parent); //弹出“透明”
  11.             4.testFuc.call(window); //弹出“透明”
  12.             5.testFuc.call(testObj); //弹出“红色”
  13.         });
  14. </script>

上面这段代码演示了call的作用。第一个函数调用,this指向了window,所以弹出了window的color属性。

第二个函数可能有些朋友以为也会弹出透明,但是请先确定我们的函数运行在$(function(){});中,这个jQuery的函数,了解jQuery的朋友都很清楚,在

$(function(){});中this的作用域指向的是document,然后我们调用testFunc,要弹出document的color,当然是未定义的。

第三个函数将testFunc的this指向了document的亲爹window,弹出window的color当然也是没有问题的。

第四个函数就更加直白了,把window传进去了

第五个函数,将testFunc的this指向了testObj,弹出了红色。

讲到这里,用法大家应该都有所了解了,但是具体怎么去理解怎么去使用还是看自己的套路。

我是这么理解的,可以把这种用法看成是C#或者java中的泛型方法。比如一个C#方法的定义

  1. public void Test<T>(T a, T b) { }

这样我们就可以实现对方法的扩展,实现通用的目的。

以上都是本人自己的看法和观点,有什么不对之处还请大家指出来共同学习。

108 Responses to “ js中Function的apply方法与call方法理解 ”

  1. suba me说道:

    B0aW3N uvb treatment What are the laws on republishing newspaper articles in a book? Are there copyright issues?

  2. to read more说道:

    Spot on with this write-up, I truly feel this site needs a great deal more attention. I all probably be returning to read through more, thanks for the advice!

  3. coloring说道:

    Wow, what a video it is! Actually nice feature video, the lesson given in this video is truly informative.

  4. Thank you for your post.Much thanks again. Fantastic.

  5. sayt krovla说道:

    visit this site and be up to date all the time.

  6. Wow! Thank you! I continually wanted to write on my site something like that. Can I implement a portion of your post to my blog?

  7. Oluwadamilare说道:

    So happy to get discovered this post.. Excellent ideas you possess here.. I value you blogging your perspective.. I value you conveying your perspective..

  8. I think this is a real great blog. Keep writing.

  9. More hints说道:

    I value the blog post.Much thanks again. Awesome.

  10. rhenk you for rhw ripd. Ir hwkpwd mw e kor.

  11. kuznica Tolyatti说道:

    Pretty! This has been a really wonderful article. Thank you for providing this info.

  12. My brother suggested I may like this website. He used to be totally right.

  13. It’а†s actually a cool and helpful piece of info. I am satisfied that you just shared this useful information with us. Please keep us up to date like this. Thank you for sharing.

  14. Really appreciate you sharing this blog post. Will read on

  15. Some really wonderful articles on this internet site , thankyou for contribution.

  16. Looking forward to reading more. Great blog post. Much obliged.

  17. wow, awesome post.Really thank you! Will read on

  18. Of course, what a great blog and educative posts, I will bookmark your site.Have an awsome day!

  19. Yeah bookmaking this wasn at a bad decision great post!.

  20. Very good info. Lucky me I ran across your website by accident (stumbleupon). I ave book-marked it for later!

  21. klm promo code说道:

    This very blog is without a doubt entertaining additionally factual. I have discovered helluva helpful stuff out of it. I ad love to come back again and again. Thanks!

  22. This is a really great examine for me, Must admit that you are a single of the best bloggers I ever saw.Thanks for posting this informative article.

  23. Thanks so much for the article post.Much thanks again. Much obliged.

  24. metal recycling说道:

    Wow, great blog article.Really thank you! Want more.

  25. I really love your website.. Excellent colors & theme. Did you develop this web site yourself?

  26. Pretty! This was an extremely wonderful post. Many thanks for providing this info.

  27. This is one awesome post.Really thank you! Cool.

  28. thao duoc quy说道:

    Keep up the great work , I read few posts on this internet site and I believe that your blog is rattling interesting and contains bands of great information.

  29. I want to start a blog/online diary, but not sure where to start..

  30. Tattoo Shop说道:

    Thanks so much for the article post.Really thank you! Keep writing.

  31. Thank you for sharing this great article. Very inspiring! (as always, btw)

  32. I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are wonderful! Thanks!

  33. Online说道:

    Way cool! Some extremely valid points! I appreciate you penning this article plus the rest of the website is really good.

  34. visit website说道:

    Say, you got a nice article.Much thanks again. Keep writing.

  35. Blogging说道:

    Muchos Gracias for your blog article.Really looking forward to read more.

  36. beauty说道:

    Very good blog post.Much thanks again. Awesome.

  37. Thanks-a-mundo for the article.Really thank you! Want more.

  38. Hosting说道:

    This website was how do you say it? Relevant!! Finally I ave found something which helped me. Cheers!

  39. Your style is so unique compared to other people I have read stuff from. Many thanks for posting when you ave got the opportunity, Guess I all just book mark this blog.

  40. You made some clear points there. I did a search on the subject matter and found most individuals will consent with your website.

  41. Polainas tejidas说道:

    Its hard to find good help I am forever proclaiming that its hard to find quality help, but here is

  42. Sisimiut说道:

    Thanks for one as marvelous posting! I definitely enjoyed reading it,

  43. my page说道:

    Very nice post and straight to the point. I am not sure if this is actually the best place to ask but do you guys have any thoughts on where to hire some professional writers? Thank you

  44. white shoes说道:

    This is a very good tip particularly to those new to the blogosphere. Short but very accurate information Many thanks for sharing this one. A must read article!

  45. value说道:

    you wish be delivering the following. unwell unquestionably come more formerly again as exactly the

  46. bot pho mai说道:

    Merely wanna comment that you have a very decent web site, I enjoy the design it really stands out.

  47. Tel Aviv Escorts说道:

    you have got an incredible blog right here! would you wish to make some invite posts on my weblog?

  48. Waec expo说道:

    Wow, great article post.Much thanks again. Really Cool.

  49. Nice blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my website loaded up as fast as yours lol

  50. This website truly has all the info I needed concerning this subject and didn at know who to ask.

  51. Thanks for sharing, this is a fantastic blog.Really thank you! Awesome.

  52. Pretty! This has been a really wonderful article. Many thanks for providing this info.

  53. This unique blog is really awesome as well as factual. I have discovered a lot of useful tips out of this amazing blog. I ad love to come back over and over again. Cheers!

  54. Valuable info. Lucky me I found your website by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  55. Wow! This could be one particular of the most helpful blogs We ave ever arrive across on this subject. Actually Wonderful. I am also an expert in this topic therefore I can understand your effort.

  56. Wow, great blog article.Really looking forward to read more. Keep writing.

  57. cris urzua说道:

    I think this is a real great article.Much thanks again. Fantastic.

  58. Very good article post.Really thank you! Want more.

  59. say about this article, in my view its in fact

  60. Really informative blog article.Thanks Again. Great.

  61. junior说道:

    Replica Oakley Sunglasses Replica Oakley Sunglasses

  62. Judi Tembak Ikan说道:

    Say, you got a nice blog post.Much thanks again. Really Great.

  63. hotels说道:

    You have brought up a very wonderful points , appreciate it for the post.

  64. your presentation however I find this topic to be really one thing

  65. I truly appreciate this blog post.Much thanks again. Really Cool.

  66. What as Happening i am new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I hope to contribute & help other users like its helped me. Good job.

  67. take a look at说道:

    Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is magnificent, let alone the content!

  68. Its hard to find good help I am regularly proclaiming that its difficult to get quality help, but here is

  69. Looking forward to reading more. Great blog article.Really thank you! Awesome.

  70. Pretty! This was an incredibly wonderful article. Many thanks for supplying this information.

  71. Bump on the Gum说道:

    Very informative blog.Really looking forward to read more. Great.

  72. Winners说道:

    topic of unpredicted feelings. Feel free to surf to my web blog; how to Get rid Of dark Circles

  73. know more说道:

    You have brought up a very good points , thanks for the post.

  74. It’а†s really a great and helpful piece of info. I’а†m happy that you simply shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

  75. visit website说道:

    pretty helpful material, overall I imagine this is worth a bookmark, thanks

  76. This is my first time go to see at here and i am in fact impressed to read all at single place.

  77. This website certainly has all of the information I wanted concerning this subject and didn at know who to ask.

  78. go to说道:

    Nice blog here! Also your website loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

  79. view说道:

    What as Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I hope to contribute & assist other users like its aided me. Great job.

  80. Thanks so much for the blog.Really thank you! Want more.

  81. It as hard to come by well-informed people about this topic, however, you sound like you know what you are talking about! Thanks

  82. Dia说道:

    This is a topic that is near to my heart Take care! Exactly where are your contact details though?

  83. I reckon something genuinely interesting about your blog so I saved to bookmarks.

  84. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, as well as the content!. Thanks For Your article about sex.

  85. It as difficult to find knowledgeable people for this subject, however, you seem like you know what you are talking about! Thanks

  86. Thanks a lot for the post.Really thank you! Keep writing.

  87. You have made some really good points there. I checked on the web to learn more about the issue and found most individuals will go along with your views on this website.

  88. post说道:

    You ave got a great blog there keep it up. I all be watching out for most posts.

  89. ndu说道:

    I truly appreciate this post.Really looking forward to read more. Want more.

  90. see the website说道:

    This website was how do you say it? Relevant!! Finally I have found something which helped me. Thanks!

  91. miller electric说道:

    wow, awesome article post.Much thanks again. Keep writing.

  92. premium ads说道:

    There is visibly a bunch to know about this. I think you made some good points in features also.

  93. I truly appreciate this article post.Thanks Again. Keep writing.

  94. This site was how do you say it? Relevant!! Finally I ave found something that helped me. Thank you!

  95. Really informative blog article.Really thank you! Awesome.

  96. you have an excellent blog right here! would you wish to make some invite posts on my weblog?

  97. caratulas CD说道:

    Thanks again for the article post.Thanks Again. Awesome.

  98. view说道:

    There as a lot of folks that I think would

  99. Very good post. I will be dealing with many of these issues as well..

  100. cau do说道:

    Really informative post.Thanks Again. Fantastic.

  101. official site说道:

    I think other web-site proprietors should take this website as an model, very clean and magnificent user friendly style and design, as well as the content. You are an expert in this topic!

  102. more info说道:

    Peculiar article, just what I wanted to find.

  103. I value the blog.Much thanks again. Awesome.

  104. Very good blog post. I certainly love this site. Keep it up!

  105. click here说道:

    This is one awesome blog article.Thanks Again.

  106. good day说道:

    incredibly great submit, i really appreciate this internet internet site, carry on it

  107. Preferably, any time you gain understanding, are you currently in a position to thoughts updating your internet site with an increase of info? It as pretty ideal for me.

  108. Really appreciate you sharing this article post.Much thanks again. Keep writing.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>