程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

JavaScript中的各种函数以及this指向

发布于2021-11-08 05:42     阅读(1306)     评论(0)     点赞(0)     收藏(0)


1、普通函数

this指向window对象

  1. function fn(){
  2. console.log(this); // Window
  3. }
  4. fn()

2、对象中的方法

this指向该方法的所属对象

  1. const obj = {
  2. say:function(){
  3. console.log(this); //{say: ƒ}
  4. }
  5. }
  6. obj.say()

3、构造函数

this指向构造函数的实例化对象(原型上的方法同样如此)

  1. function Person(){
  2. Person.prototype.say = function(){
  3. console.log(this); // Person {}
  4. }
  5. }
  6. const hzy =new Person()
  7. hzy.say()

4、绑定事件函数

this指向事件绑定的对象

  1. const btn = document.querySelector('button');
  2. btn.onclick = function(){
  3. console.log(this); // <button>123</button>
  4. }

 5、定时器函数

this指向window对象

  1. setTimeout(() => {
  2. console.log(this); // // Window
  3. }, 1000);

6、立即执行函数

this指向window对象

  1. (function(){
  2. console.log(this); // window
  3. })()

7、箭头函数

箭头函数没有自己this指向,里面的this指向外层作用域(如果箭头函数外层有函数,那么外层函数的this就是箭头函数的this,如果没有,则this指向window)

  1. //箭头函数外层没有函数
  2. let sum = (x,y)=>{
  3. console.log(this); //Window
  4. return x + y;
  5. }
  6. sum(1,2)
  7. //箭头函数外层有函数
  8. const btn = document.querySelector('button');
  9. btn.onclick = function () {
  10. let sum = (x, y) => {
  11. console.log(this); //this指向btn
  12. return x + y;
  13. }
  14. sum(1, 2)
  15. }

原文链接:https://blog.csdn.net/hzylearning/article/details/121187803




所属网站分类: 技术文章 > 博客

作者:小兔崽子

链接:http://www.qianduanheidong.com/blog/article/220001/d104ed1c93ed664fa806/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)