this指向

在函数调用中(指向window)

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

在对象调用函数中(指向调用这个函数的对象)

let Obj = {
  name: "LLC",
  say: function() {
    console.log(this);
  }
}
Obj.say(); //Obj对象
let func = Obj.say;
func(); //window

在构造函数中(指向实例出来的对象)

function Person(name, gender) {
  this.name = name;
  this.gender = gender;
  console.log(this);
}
let p = new Person('LLC', '男');  //Person的实例对象p

在 call apply bind 中(指向替代对象)

let Obj1 = {
  name: "LLC",
  say: function() {
    console.log(this);
  }
}
let Obj2 = {
  name: "ASJ"
}
Obj1.say.call(Obj2);  //{name: "ASJ"}

在箭头函数中(指向调用这个函数的外层对象)

Example_01:
let Obj = {
  name: "LLC",
  say: () => {
    console.log(this);
  }
}
Obj.say(); //window
Obj调用say函数,Obj的外层对象是window

Example_02:
function Person(name) {
  let Obj = {};
  Obj.name = name;
  Obj.say = () => {
    console.log(this);
  }
  return Obj;
}
let p = new Person();
p.say();
上一篇:Golang | Go语言多态的实现与interface使用


下一篇:codewars练习知识总结