Day2-this的9种使用场景

128 阅读1分钟

Day2 打卡 this使用场景

每日一句

You can't let someone else's opinion tear you down.

你不能让别人的意见把你打倒。

this的使用场景

  • 普通函数中,this->Window
function play() {
    console.log(`this >>> ${this}`)
}
  • 构造函数中, this -> new出来的实例对象
function Base(name){
    this.name = name
    console.log(`this >>> ${this}`)
}
var stu = new Base('stu');
Base();// 如果直接运行就如同普通函数 this->Window
  • 构造函数 prototype 中, this->new出来的实例对象
fucntion Fn(name){
  this.name = name
}
Fn.prototype.say() {
  console.log(this.name)
}
  • 匿名函数中,this->Window
// ()()
(function(){
  console.log(this)
})();

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

// !
!function(){
console.log(this)
}();
  • 定时器中,this-> Window(本质也是匿名函数)
var name = 'zhangsan';
var timer = setTimeout(function(){
  var name = 'lisi';
  console.log(this.name);
  clearTimeout(timer)
});

  • 对象中,this -> 最近一层的对象(可能有多层级)
var obj = {
  name: 'zhangsan',
  child: {
    name: 'sun',
    getName: function() {
       console.log(this, this.name)
    }
  },
  getName: function() {
    console.log(this, this.name)
  }
}
obj.getName();
obj.child.getName();
  • class类中,this->new出来的实例
class A {
  constructor(name) {
    this.name = name
    console.log(this)
  }
}
var a1 = new A('aaa');
  • call/apply/bind中, this->指定传入的对象
var name = 'window';
var obj = {
 name: 'obj'
}
function out() {
  console.log(this.name)
}

out();
out.call(obj, name);
out.apply(obj, [name]);
out.bind(obj)();
  • 箭头函数中, this->需要根据词法环境决定
var name = 'window'
var obj = {
  name: 'zhangsan',
  getName: function() {
    console.log(this.name)
  },
  getValue: () => {
    console.log(this.name)
  },
  getThis: function() {
    return () => {
      console.log(this.name)
    }
  }
}

obj.getName(); // zhangsan
obj.getValue(); // window
obj.getThis()(); // zhangsan
  • Dom事件中,this->dom节点
let elm = document.querySelector('div');
elm.onclick=function(){
  console.log(this);
}

总结

① 普通函数的调用,this指向的是window
② 构造函数及prototype的调用,this指的是实例化的新对象
③ 匿名函数的调用,this指向的是全局对象window
④ 定时器中的调用,this指向的是全局变量window
⑤ 对象方法的调用,this指的是该对象,且是最近的对象
⑥ class中的调用,this指向的是实例化的新对象
⑦ apply,call,bind,this指向参数中的对象
⑧ 箭头函数中的调用,this需要根据上下文决定
⑨ dom中的调用,this指向的是dom节点