函数this的指向
this的指向,这个确实比较难以搞懂,那么今天就来谈谈this的指向到底是指向哪里呢,先说说什么是this
在js中this确实是个难点,有时候,确实一下搞不清this到底是指向的哪里,在js里this是关键字,始终指向一个对象,是一个指针
this的指向不是由定义this而决定的,随着解析来的
1.1、在全局作用域里this始终指向window,来举个栗子
console.log(this === window); //true
console.log(window.alert === this.alert); //true
console.log(this.parseInt(“021”,10 ));//021
var book = “钢铁”; // 定义一个全局变量,等同于window.book = "钢铁"
1.2、函数作用域 this由谁调用就指向谁,也就是普通函数的this指向调用者
Function myFun()
{
console.log(this);
//window
}
myFun(); //这里其实是window.myFun()
1.2.1 严格模式下的全局作用域里this指向window
“use strict”
this.a = “u”;
console.log(this === window); //u
console.log(a); //u
1.2.2 严格模式下的函数环境下,this为undefined
function myFun()
{
“use strict”
console.log(this); //window
}
myFun === undefined; //true
1.3、箭头函数下的this指向,这里要明确以下三点
a. 箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的
b. 箭头函数中的this始终指向父级对象
c. call() apply() bind() 方法对于箭头函数来说只是传入参数, 对于 this 无影响。
这里箭头函数的this指向是声明时的外部作用域的this,箭头函数里没有自己的this而是引用外部的this,举个栗子:
var obj = {
name: 'zs',
myFun: () =>{
console.log(this);
}
}
obj.myFun();
//对象内的this调用时一般指向obj,而箭头函数在创建时就指向了obj的父级对象window,所以这里输出的结果是一个空的对象