一、简单认识this对象
- 核心一句话 - 哪个对象调用函数,函数里面的this指向哪个对象。
- 浏览器解析器在调用函数时每次都会向函数内部传递一个隐含的参数,这个隐含的参数就是this,this指向的是一个对象,这个对象我们称之为函数执行的上下文对象。
- 根据函数的调用方式的不同,this会指向不同的对象,这也是this的存在的意义所在。
二、this指向的几种情况
1、this在js中指向Window
console.log(this); // Window
2、函数中this指向Window
function fn() {
console.log(this);
}
window.fn(); // Window
3、数组中存放的函数,被数组索引之后加圆括号调用,this就是这个数组
function fn(){
console.log(this) // (3) ['a', 'b', ƒ]
}
var arr = ['a', 'b', fn]
arr[arr.length-1]()
4、函数作为一个对象的方法,对象调用方法,函数的this就是这个对象
var obj = {
name: '张三',
say(){
console.log(this) // {name: '小何', say: ƒ}
console.log(this.name) // 张三
}
obj.say()
5、定时器调用函数时,this是Window对象
setInterval(function(){
console.log(this) // window
}, 1000)
6、DOM0级事件的回调函数中this指向 Window(行内绑定事件函数)
点我点我!
function fn1() {
console.log(this); // Window
}
7、函数是事件处理函数时,函数的this就是触发这个this的对象
document.querySelector('button').onclick = function(){
console.log(this) //
}
8、标签中指向当前标签
点我点我!
function fn2(obj) {
console.log(obj); // 点我点我!
}
9、箭头函数中的this指向宿主对象
let fn = () => {
console.log(this); // Window
}
fn();
let obj = {
name: '张三',
say() {
function fn() {
console.log(this, 111); // Window 111
}
fn();
let fn1 = () => {
console.log(this, 222); // {name: '张三', say: ƒ} 222
}
fn1();
}
}
obj.say();
三、this指向的改变
call方法
作用: 调用该函数,并修改函数中this的指向为第一个参数
语法: 函数名. call(对象,实参1,实参2);
function fn(name, age) {
this.name = name;
this.age = age;
console.log(this); // {info: '啦啦', name: '李四', age: 22}
}
let f = new fn('张三', 18);
let obj = {
info: '啦啦'
}
fn.call(obj, '李四', 22);
apply 方法
作用: 调用该函数,并修改函数中this的指向为第一个参数
语法: 函数名. apply(对象,数组);
function fn(x, y) {
console.log(this); // {a : 1}
console.log(x + y); // 8
}
fn.apply({
a: 1
}, [3, 5]);
bind方法
作用: 不调用函数,克隆一个新的函数,并修改新函数中this的指向为第一个参数,将新的函数返回
语法: 函数名. bind(对象,[实参]);
function fn(x, y) {
console.log(this); // {b:2}
console.log(x + y); // 8
}
var newFn = fn.bind({
b: 2
}, 3, 5);
newFn();
补充
在严格版中的默认的this不再是window,而是undefined。