javascript-this指向问题

2021/12/26 22:09:40

本文主要是介绍javascript-this指向问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

this指向问题

1: 普通函数调用,this指向window

 function a() { // 严格模式下  this为undefined
     console.log(this) // window
 }
 在node.js中运行的话,this指向global全局对象
 

2: 谁调用指向谁

 let obj = {
  name: '张三',
  age: 10,
  fn3() {
      console.log(this)
  }
}

obj.fn3() // this指向obj

扩展
 let obj = {
  name: '张三',
  age: 10,
  fn3() {
      console.log(this)
  }
}
let obj1 = obj.fn3
obj1() // window ,此时this指向的是window

3. 构造函数中this指向实例化的对象

let Animal = function() {
  console.log("this",this);
}

var animal = new Animal() //Animal {}

4.箭头函数的this,捕获上下文的this

var name = '李四'
let obj2 = {
  name: '张三',
  age: 18,
  action:()=>{
    console.log("this",this.name);
  }
}
obj2.action() // 李四

5.call和apply bind 可以改变this的指向

 let obj = {
  name: '张三',
  age: 10,

}
function f3() {
    console.log(this)
}
 fn3.apply(obj) // obj // call 和 bind类似
 只不过 call 传递的参数是以逗号分隔的
 bind需要再次调用
 

6.定时器的this指向window

// 定时器中的this指向window
setTimeout(function() {
  console.log("this",this); // window
})



7. 回调的this指向window

let fn5 = function(callback) {
  callback()
}
function callback() {
  console.log("this",this); // window
}
fn5(callback)

let p = new Promise((resolve,reject)=>{
  resolve(1)
})
p.then((res)=>{
 console.log("this",this); // window
})

8 箭头函数和普通函数的区别

 1: 箭头函数的this指向上下文的this
 2: 箭头函数是函数表达式的简写,没有函数提升
 3: 箭头函数没有自己的arguments,使用rest剩余参数代替
 4: 箭头函数没有自己的原型,不可以做为构造函数
 5:箭头函数没有yield属性,也就不能做为生成器generate来使用
 6:箭头函数不可以通过call apply 和bind改变this指向


这篇关于javascript-this指向问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程