this的指向问题、bind/call/apply改变this指向

this的指向问题

全局作用域下的this指向

无论是否是严格模式,全局作用域下的this始终指向window


函数内部的this

严格模式下:

function test() {
  'use strict'
  console.log(this)
}
test(); // undefined
window.test(); // window

非严格模式下:

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

严格模式下,对函数的调用必须严格地写出被调用函数的对象,不可以省略。非严格模式,可以省略。


对象内部方法的this

对象内部方法的this指向调用这些方法的对象,也就是谁调用就指向谁

let obj = {
  test: function() {
    console.log(this);
  }
}
obj.test(); // obj

箭头函数中的this

箭头函数没有this,它会绑定最近的非箭头函数作用域中的this。从父级作用域一直往上找,直到找到this的指向为止。

let obj = {
  test: () => {
    console.log(this);
  }
}
obj.test(); // window

如果test是普通函数,那么它的this应该绑定的是obj。

然而test现在是箭头函数,因此它的this要找到obj的父级作用域,也就是window,因此this指向window。


构造函数中的this

构造函数中的this是指向实例的。

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

let p = new Person("cxk", 20, 'girl');
console.log(p.name); // cxk
console.log(p.age); // 20
console.log(p.sex); // girl

bind/call/apply 改变this指向

三个方法的区别:

他们都是用来改变相关函数的this指向的。

但是call/apply是直接进行相关函数的调用;bind不是执行相关函数,而是返回一个新的函数,这个新的函数已经自动绑定了新的this指向。

var user = {
  test: function() {
    console.log(`My name is ${this.name}, ${this.age} years old.`);
  },
  test2: function(from, to) {
    console.log(`My name is ${this.name}, ${this.age} years old. I'm from ${from}, Iwana go to ${to}`);
  }
}

var db = {
  name: 'CXK',
  age: 18
}

user.test.call(db);
user.test.apply(db);
user.test.bind(db)();
// My name is CXK, 18 years old.

user.test2.call(db, 'beijing', 'shanghai');
user.test2.apply(db, ['beijing', 'shanghai']);
user.test2.bind(db, 'beijing', 'shanghai')();
// My name is CXK, 18 years old. I'm from beijing, I wanna go to shanghai.
posted @ 2022-08-25 09:08  笔下洛璃  阅读(49)  评论(0编辑  收藏  举报