你怎么还没搞懂 this?

4个月前的那篇《this 的值到底是什么?一次说清楚 – 知乎专栏》已经把 this 的来龙去脉说清楚了,可以搞定面试遇到的所有相关题目。

不过实际项目中 this 的使用事情可能要更晦涩一点,我们就举例来说说。

本文用到的所有知识,依然来自《this 的值到底是什么?一次说清楚 – 知乎专栏》。

Event Handler 中的 this

btn.addEventListener('click' ,function handler(){
  console.log(this) // 请问这里的 this 是什么
})

handler 中的 this 是什么呀,看了你的文章我还是不懂啊?

那是因为你没有看懂,我们说过 this 都是由 call 或 apply 指定的,那么你只需要找到 handler 被调用时的代码就行了。

可是我哪知道 addEventListener 的源代码呀

是呀,addEventListener 是浏览器内置的方法,我们看不见源代码。

所以,你只能看文档了,MDN 这样说:

通常来说this的值是触发事件的元素的引用,这种特性在多个相似的元素使用同一个通用事件监听器时非常让人满意。

当使用 addEventListener() 为一个元素注册事件的时候,句柄里的 this 值是该元素的引用。其与传递给句柄的 event 参数的 currentTarget 属性的值一样。

由于浏览器知道你不方便看源码里是怎么 call handler 的,所以直接在文档里告诉你了,你可以假想浏览器的源码是这样写的:

// 当事件被触发时
handler.call(event.currentTarget, event) 
// 那么 this 是什么不言而喻

jQuery Event Handler 中的 this

那么下面代码中的 this 是什么呢:

$ul.on('click', 'li' , function(){
  console.log(this)
})

同样,不要瞎猜,你要么看 jQuery 源码是怎么 call 这个函数的,要么看jQuery 文档

jQuery 文档是这样写的:

当jQuery的调用处理程序时,this关键字指向的是当前正在执行事件的元素。对于直接事件而言,this 代表绑定事件的元素。对于代理事件而言,this 则代表了与 selector 相匹配的元素。(注意,如果事件是从后代元素冒泡上来的话,那么 this 就有可能不等于 event.target。)若要使用 jQuery 的相关方法,可以根据当前元素创建一个 jQuery 对象,即使用 $(this)。

总结一下如何确定 this 是值

  1. 看源码中对应的函数是怎么被 call 的(这是最靠谱的办法)
  2. 看文档
  3. console.log(this)
  4. 不要瞎猜,你猜不到的

如何强制指定 this 的值?

自己写 call / apply 即可:

function handlerWrapper(event){
  function handler(){
    console.log(this) // 请问这里的 this 是什么
  }

  handler.call({name:'饥人谷'}, event)
}
btn.addEventListener('click', handlerWrapper)

你也可以直接使用 bind,与上面的代码效果差不多:

function handler(){
  console.log(this) // 请问这里的 this 是什么
}
var handlerWrapper = handler.bind({name:'饥人谷'})
btn.addEventListener('click', handlerWrapper)

上面三句代码可以挤成一句:

btn.addEventListener('click', function(){
  console.log(this) // 请问这里的 this 是什么
}.bind({name:'饥人谷'}))

这是前端里一个常见的套路。

this 不难,就看你有没有按照 call / apply 来理解函数了。

完。

作者:方应杭

57 thoughts on “你怎么还没搞懂 this?”

  1. My brother recommended I might like this blog. He used to be entirely right. This put up actually made my day. You can not believe simply how so much time I had spent for this information! Thank you!|

  2. Hello there, I discovered your web site by the use of Google even as searching for a comparable matter, your site came up, it seems to be great. I’ve bookmarked it in my google bookmarks.

  3. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is valuable and everything. But just imagine if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with pics and video clips, this blog could certainly be one of the best in its field. Very good blog!|

  4. I just like the valuable info you supply for your articles. I will bookmark your blog and test again here regularly. I am somewhat sure I will learn plenty of new stuff proper right here! Good luck for the next!|

  5. I like the helpful info you provide in your articles. I will bookmark your blog and check again here frequently. I’m quite sure I’ll learn a lot of new stuff right here! Best of luck for the next!|

  6. Hi there! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!|

  7. Simply want to say your article is as astonishing. The clearness in your post is just nice and i could assume you’re an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.|

  8. Good day I am so thrilled I found your web site, I really found you by mistake, while I was searching on Yahoo for something else, Anyhow I am here now and would just like to say kudos for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the excellent jo.|

  9. Howdy are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!|

  10. Great beat ! I would like to apprentice whilst you amend your website, how could i subscribe for a weblog site? The account aided me a appropriate deal. I had been tiny bit acquainted of this your broadcast offered shiny transparent concept|

  11. I used to be recommended this website via my cousin. I’m not sure whether or not this post is written via him as nobody else recognise such targeted approximately my problem. You’re amazing! Thanks!|

  12. Hello! Do you use Twitter? I’d like to follow you if that would be ok. I’m absolutely enjoying your blog and look forward to new posts.|

  13. Greetings from Florida! I’m bored to death at work so I decided to browse your site on my iphone during lunch break. I enjoy the information you present here and can’t wait to take a look when I get home. I’m surprised at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyways, superb site!|

  14. I used to be recommended this web site by means of my cousin. I’m no longer sure whether or not this post is written through him as no one else recognize such exact approximately my trouble. You’re wonderful! Thank you!|

  15. Howdy! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your articles. Can you recommend any other blogs/websites/forums that cover the same topics? Thanks for your time!|

  16. My spouse and I absolutely love your blog and find almost all of your post’s to be exactly I’m looking for. Would you offer guest writers to write content in your case? I wouldn’t mind writing a post or elaborating on a number of the subjects you write related to here. Again, awesome web site!|

  17. Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.|

  18. Great beat ! I would like to apprentice even as you amend your site, how can i subscribe for a weblog site? The account helped me a acceptable deal. I had been a little bit familiar of this your broadcast provided brilliant clear idea|

  19. Howdy! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!|

  20. Have you ever considered about including a little bit more than just your articles? I mean, what you say is important and everything. Nevertheless think of if you added some great images or video clips to give your posts more, “pop”! Your content is excellent but with images and clips, this site could certainly be one of the very best in its field. Fantastic blog!|

  21. I feel that is one of the so much important information for me. And i’m glad studying your article. However want to statement on few normal issues, The website style is ideal, the articles is truly nice : D. Just right activity, cheers|

  22. I’m really inspired with your writing skills as well as with the layout on your blog. Is that this a paid theme or did you modify it yourself? Either way stay up the nice high quality writing, it’s rare to peer a great weblog like this one these days..|

发表评论

电子邮件地址不会被公开。