JavaScript- this

66 阅读1分钟

一、什么是this

执行上下文中包含变量环境、词法环境、外部环境、this。执行上下文有全局执行上下文和函数执行上下文。

全局执行上下文中的this:指向window对象。

函数执行上下文中的this:默认情况下调用一个函数,this指向window对象。怎么改变其this的指向呢?

二、有哪些改变this的方法

1、call、bind、apply改变this的指向

//apply 
func.apply(thisArg, [argsArray])

//call
fun.call(thisArg, arg1, arg2, ...)

//bind
const newFun = fun.bind(thisArg, arg1, arg2, ...)
newFun()

//apply和call就是传参不一样,但是两个都是会在调用的时候同时执行调用的函数,
//但是bind则会返回一个绑定了this的函数.

2、对象调用内部的方法时,this指向对象本身

var myObj = {
  name : "极客时间", 
  showThis: function(){
    console.log(this)
  }
}
myObj.showThis()

三、注意点

1、箭头函数没有this,它会使用外层函数的this

2、this是不会继承的

3、多去找一些关于this的面试题刷一刷