
一、谁调用指向谁
1、直接调用指向window
function fn() {
console.log(this)
}
fn()
2、对象调用指向对象
const obj = {
fn: function () {
console.log(this)
}
}
obj.fn()
二、构造函数this指向实例化对象
function obj_fn() {
this.fn = function () {
console.log(this)
}
}
const xxx = new obj_fn()
xxx.fn()
三、箭头函数this指向
const fn1 = () => {
console.log(this)
}
const obj = {
fn2: () => {
console.log(this)
},
fn3: function () {
return () => {
console.log(this)
}
}
}
fn1()
obj.fn2()
obj.fn3()()
四、修改this指向
1、call() 使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数
语法:function.call(thisArg, arg1, arg2, ...)
- thisArg:this指向的目标,不传默认执行全局对象
- arg...:其他参数
function Father(name, age) {
this.name = name
this.age = age
this.book = ['数据结构', '计算机网络', '算法']
}
function Sun(name, age) {
Father.call(this, name, age)
}
const sun1 = new Sun('gxm', '20')
sun1.book.push('javaScript')
console.log(sun1.book)
const sun2 = new Sun('xz', '22')
console.log(sun2.book)
2、apply() 使用一个指定的 this 值和数组或类数组对象来调用一个函数
语法:function.apply(thisArg, argsArray)
- thisArg:this指向的目标,不传默认执行全局对象
- argsArray:数组或类数组对象
function num_arr() {
this.num = [1, 2, 3]
}
function fn(name, age) {
num_arr.call(this)
}
const obj = new fn()
obj.num.push(4)
console.log(obj.num)
3、bind() 返回一个函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
this.x = 1
const obj = {
x: 2,
getX: function () {
return this.x
}
}
console.log(obj.getX())
const window_getX = obj.getX
console.log(window_getX())
const bind_obj_getX = window_getX.bind(obj)
console.log(bind_obj_getX())