JavaScript---this、箭头函数

122 阅读2分钟

JS中的this

普通函数:谁调用(this)就指向谁

image.png

// 普通函数调用
function fn() {
    console.log("普通函数调用", this); // 输出window
}
/*
  * window.fn = function() {}
 */
 fn(); // window
 window.fn(); // window

//  构造函数调用
 function Person() {
   console.log("构造函数调用", this); // 输出Person对象,指向自己
 }
 var p1 = new Person();
 
// 对象方法调用
var obj = {
   sayHi:function () {
      console.log("对象方法调用", this); // 输出obj对象
    }
 };
 obj.sayHi();
 
//  事件绑定调用
document.onclick = function () {
  console.log("事件绑定调用方法" , this);  // #document
}
 
// 定时器函数调用 window.setInterval
setInterval(function () {
  console.log("定时器函数调用", this); // window
},1000)

箭头函数:调用者指向谁,(this)则指向谁。指向函数声明时所在作用域下的对象,而不是运行时所在的对象。

image.png

如何改变this的指向

  • 利用call、apply、bind方法
  • 通过变量将需要的this存储下来:let _this = this
  • 借用其他对象的方法:构造函数、arguments

call、apply、bind函数,区别

const obj = {
   a:100
}
function sum(x,y){
 console.log(this.a+x+y)
}
sum(3,7)// undefined+ 3+7 = NaN,
解析:[直接调用,this指向window,window下没有a属性,window.a = undefined]
// 1.call[第一个参数是新的this指向,从第二个参数开始表示函数自身的参数]
sum.call(obj,3,7) // 100 + 3+7 = 110
// 2.apply【第一个参数是新的this指向,第二个参数是一个数组或者类数组,值依然是函数自身的参数】
sum.apply(obj,[3,7]) // 110
// 3.bind
[第一个参数是新的this指向,从第二个参数开始表示函数自身的参数]
[bind是返回对应函数体,便于后面调用]
sum.bind(obj,3,7)() // 110,【需要再次调用】【call,apply是立即调用】

箭头函数与普通函数的区别

  • this指向不同
    • 普通函数,内部的this指向函数运行时所在的对象
    • 箭头函数没有自己的this对象,内部的this是定义时上层作用域中的this
  • 箭头函数是匿名函数,不能使用new操作符
  • 箭头函数没有原型属性

什么情况不能使用箭头函数?

  • 构造函数中不能使用箭头函数
function Test(name,age){
  this.name = name
  this.age = age
}
let fn = new Test('tom',12)
console.log(fn.name) // tom

// 创建一个构造函数
const Test2 = (name,age)=>{
 this.anme = name
 this.age = age
}
let fn2 = new Test2('lina',12)
console.log(fn2.name) // 报错,fn2 is not a constructor
  • 监听事件中需要使用this时不建议使用箭头函数
dom.addEventListener('click',()=>{
  console.log('this',this)  // this指向window
})
  • 对象的方法,不建议使用箭头函数
let obj = {
 key:'key',
 getKey:()=>{
   return this.key
 }
 getKey2(){
   return this.key
 }
}
obj.getKey();//this指向window,返回值取决于window中是否有对应的属性
obj.getKey2();// this指向obj,返回'key'
  • 对象的原型的方法,不建议使用箭头函数
let obj = {
 key:'key'
}
obj._proto_getKey =()=>{
 console.log('this',this) //this指向window
 return this.key
}
obj.getKey()
  • Vue的生命周期及methods中的方法不建议使用箭头函数:this指向的是window对象