JavaScript-this指向问题

默认值

1.1普通函数

谁调用指向谁,严格模式下没有调用者时 this 的值为 undefined

function fn() {
      console.log(this);
    }
    fn();//输出window

1.2箭头函数

箭头函数中的 this 与普通函数完全不同,也不受调用方式的影响,事实上箭头函数中并不存在 this !箭头函数中访问的 this 不过是箭头函数所在作用域的 this 变量。

 let sayHi = function () {
      console.log(this); // 该箭头函数中的 this 为函数声明环境中 this 一致
    };
    let user = {
      name: "小明",
      // 该箭头函数中的 this 为函数声明环境中 this 一致
      walk: () => {
        console.log(this);
      },

      sleep: function () {
        let str = "hello";
        console.log(this);
        let fn = () => {
          console.log(str);
          console.log(this); // 该箭头函数中的 this 与 sleep 中的 this 一致
        };
        // 调用箭头函数
        fn();
      },
    };

    // 动态添加方法
    user.sayHi = sayHi;

    // 函数调用
    user.sayHi();
    user.sleep();
    user.walk();

定义值

2.1 callcall(this,形参1,形参2...形参n)

  function sayHi() {
    console.log(this);
  }

  let user = {
    name: '小明',
    age: 18
  }

  let student = {
    name: '小红',
    age: 16}

  // 调用函数并指定 this 的值
  sayHi.call(user); // this 值为 user
  sayHi.call(student); // this 值为 student

2.2 applyapply(this,[形参1,形参2...形参n])

function counter(x, y) {
    return x + y;
  }

  // 调用 counter 函数,并传入参数
  let result = counter.apply(null, [5, 10]);
  console.log(result);

2.3 bindcall(this,形参1,形参2...形参n)
bind 方法并不会调用函数,而是创建一个指定了 this 值的新函数,使用方法如下代码所示:

 // 普通函数
  function sayHi() {
    console.log(this);
  }

  let user = {
    name: '小明',
    age: 18
  }

  // 调用 bind 指定 this 的值
  let sayHello = sayHi.bind(user);

  // 调用使用 bind 创建的新函数
  sayHello();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值