this指向

说明:

  • this 指向它所引用的对象 (this最终代表的是一个对象)

  • this指向可以更改;

  • 通过 call() 和 apply()方法 修改this指向

注意💡:

  • 全局作用域下 this 指向window
//  全局作用域下: window是顶层对象(window 对象的属性和方法拥有全局作用域, window 通常省略), this指向 window
console.log(this);
console.log(window);
  • 函数中的this 指向window
// 函数中
function fun(){
    console.log(this);
}
fun();

改变this指向:

let num = 100;
let obj = {
    num:500
}
function print(){
    console.log(this);
    this.count = 200;
    console.log(this.num);
    // console.log(this.count);
    console.log(this.count + this.num);
}
print.call()
//  修改this指向 第一个参数用来修改this指向
print.call(obj)
print.apply(obj)
posted @ 2022-04-12 17:11  秋弦  阅读(18)  评论(0编辑  收藏  举报