this指向总结

总结:

  1. 纯粹的函数调用:指向全局
  2. 作为对象方法的调用:指向对象(调用者)
  3. 构造函数调用:构造函数中的this指向new出来的对象实例
  4. apply调用:指向apply所接受的执行空间
  5. 剪头函数:指向上一级

不重要的

  • 定时器指向window
  • 事件绑定指向元素本身

一道腾讯笔试题

  var x = 20;
  var a = {
    x: 15,
    fn: function () {
      var x = 30;
      return function () {
        return this.x
      }
    }
  }
  console.log(a.fn());//返回一个函数
  console.log((a.fn())());//20
  console.log(a.fn()());//20
  console.log(a.fn()() == (a.fn())()); //true
  console.log(a.fn().call(this)); //20
  console.log(a.fn().call(a)); //15 

demo:

  var name = 'tangbohu'
  // 1.纯粹的函数调用:指向全局
  function doit() {
    alert(this.name)//'tangbohu'
  }
  doit()
  // 2.作为对象方法的调用:指向对象(调用者)
  const person = {
    name: 'xusheng',
    sayName: function () {
      alert(this.name)//xusheng
    }
  }
  person.sayName()
  // 3.构造函数调用:构造函数中的this指向new出来的对象实例
  function foo(name, age) {
    this.name = name
    this.age = age
  }
  const baby = new foo('heshang', 13);
  alert(baby.name)//heshang

  // 4.apply调用:指向apply所接受的执行空间
  name = 'window-Name'
  function testapply() {
    alert(this.name)
  }
  testapply.apply(person)//xusheng    并不是window下的window-Name

  // 5.剪头函数:指向上一级
  const person2 = {
    name: 'xusheng??????',
    sayName: () => {
      alert(this.name)//window-Name
    }
  }
  person2.sayName()

你可能感兴趣的:(this指向总结)