函数中 this 的指向,概述:
关键字 声明函数,this 指向的 区别:
function
其 this 指向,是在 函数运行的时候,确定 this 的指向。
确定关系: 对象.函数名(),只要 同时 具备了 三者,则 函数中 的 this,会指向 对象。
谁调用指向谁
注意:通过 call / apply / bind 会强制改变 this 的指向。
=>
强调:箭头函数中,并没有 this 的关键字。(注:即 箭头函数 的 call/apply/bind 无效)
那么,箭头函数中的 this,其值 是根据 声明的时候,根据 作用域的关系;
将 this 视作 变量,通过 作用域 确定 箭头函数 的this的值。
箭头函数的this是他爹的this指向,默认箭头函数中没有this ,也无法通过call/apply/bind改变指向
所有的回调函数建议都使用箭头函数
绑定事件回调函数中的this默认指向到绑定的元素,若回调函数为箭头函数,由于没有自己的this会指向window
箭头函数中 this 指向的 案例:
const f = () => {
console.log(this);
}
// f() // this 指向 `window`
const zhang = {
name: '小张',
fn: f,
sayDate: function() {
// this // this 值如何确定:根据 函数执行的时候,进行确定
setInterval(() => {
console.log(this, new Date());
}, 1000);
}
}
// zhang.fn() // this 指向 `window`
// zhang.sayDate() // 定时器中的 this 指向 `zhang`
const fn = zhang.sayDate;
// fn() // 定时器中的 this 指向 `window`
强调::回调函数 若为 箭头函数,箭头函数中的 this,指向 其上层作用域的 this。
- function 声明 函数,this 指向 如何确定:
对象.fn()只要符合该原则,则 this 指向对象,否则 指向window。 - function 声明的函数,可以通过
call / apply / bind强行改变 this 指向。
const zhang={
name:'老张',
age:20,
say(name,age){
console.log(`${this.name}的年龄是${this.age}`);
}
}
const wang = {
name:'老王',
age:18,
say(name, age) {
console.log(`${this.name}的年龄是${this.age}`);
console.log(`${name}的年龄是${age}`);
}
}
// call和apply都是立即执行 bind是返回一个新的函数
// call和bind的参数都是...args,apply的参数传递为一个数组[arg1,arg2,...]
// wang.say.call(zhang,'改变的形参1', 33);
// wang.say.apply(zhang,['改变的形参1',22]);
// 不会立即执行
// const bindFn = wang.say.bind(zhang,'形参1');
// bindFn()