一.this的指向问题:谁调用函数,函数中的this就指向谁
function fun1() {
console.log(this)
}
fun1()
function fun1() {
console.log(this)
}
window.fun1()
两者结果一样,所以如果直接调用相当于window.xxx
const obj = {
a: '1',
b: fun1
}
function fun1() {
console.log(this)
}
obj.b() //是obj.b调用的fun1函数
二.能改变this指向的有:new操作符,call,apply,bind,箭头函数
1.new操作符
function Wangcai() {
console.log(this)
}
const wc = new Wangcai()
this本应该指向window,但是通过运用new操作符之后,this指向了Wangcai()这个对象
2.call,apply,bind
function fun1() {
console.log(this)
}
const obj1 = {
name: 'aa',
age: '28'
}
fun1.call(obj1)
fun1.apply(obj1)
call和apply都能改变this指向,并立即执行函数
function fun1() {
console.log(this)
}
const obj1 = {
name: 'aa',
age: '28'
}
fun1().bind(obj1)
但是却没有输出任何东西
function fun1() {
console.log(this)
}
const obj1 = {
name: 'aa',
age: '28'
}
fun1().bind(obj1)()
结论:call和apply都会立即执行函数,但是bind不是
①.call
const obj1 = {
name: 'aa',
age: '28'
}
function fun1(a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
fun1.call(obj1, 'one', 'two', 'three') //one,two,three
②.apply
const obj1 = {
name: 'aa',
age: '28'
}
function fun1(a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
fun1.apply(obj1, 'one', 'two', 'three')
const obj1 = {
name: 'aa',
age: '28'
}
function fun1(a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
fun1.apply(obj1, ['one', 'two', 'three'])
由此可见,使用apply时,参数类型必须为数组,且数组中的每个元素都作为独立的个体,而call对参数类型没有限制。
③.bind
const obj1 = {
name: 'aa',
age: '28'
}
function fun1(a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
fun1.bind(obj1, 'one', 'two', 'three')()
fun1.bind(obj1, ['one', 'two', 'three'] )()
结论:bind方法对于参数类型没有限制,当参数为数组时,其为一个整体,数组内元素不分别独立。
总结:1.如果是普通函数调用,this指向window
2.如果是构造函数,也就是通过new调用,this指向构造函数当前new出来的实例
3.如果是对象调用函数,则this指向调用函数的对象
4.如果是使用call,apply,bind调用,则this就指向你手动在其后面设置的对象。