目录
1、以函数的形式调用时,this的指向取决于函数调用方式,调用时的上下文
4、使用call和apply调用时,this就是指定的那个对象
8、定时器 setInterval setTimeout 里面回调函数的this指向window
this是什么
任何函数本质上都是通过某个对象来调用的(看是你明确指定的还是?如果没有明确指定就是window来调用的)
所有函数内部都有一个变量,就是this!!
它的值是调用函数的当前对象
如何明确this的值
1、以函数的形式调用时,this的指向取决于函数调用方式,调用时的上下文
// 1. 函数定义, 自调用
function test(){return this}; //非严格模式下,返回window;严格模式下,返回undefined
const a = test(); // a = window;
// 2.IIFE(匿名函数自调用:立即调用函数表达式)
(function test(){return this})() //window
2、以方法的形式调用时,this就是调用方法的对象
const obj = {};
const obj2 = {};
const func = function(){return this};
obj.test = func;
obj2.test = func;
const target = obj.test(); // target = obj
const target2 = obj2.test(); // target2 = obj2;
const target3 = func; // target3 =window;
3、以构造函数的形式调用时,this就是新创建的对象
首先说明一下使用
构造函数调用函数的过程:
- 创建一个新的空对象;
- 该对象作为this参数传递给构造函数,从而成为构造函数的函数上下文;
- 如果构造函数没有返回值,新构造的对象作为new运算符的返回值;如果构造函数返回一个对象,则该对象作为整个表达式的值返回,而传入构造函数的this将被丢弃,在构造函数中对this的操作都是无效的;如果构造函数返回的是非对象类型,则忽略返回值,返回新创建的对象 这里可以参考这篇 构造函数的返回值与new实例关系
// 1. 没有返回值
function Test(){
this.func = function(){return this}
}
const a = new Test();
console.log(a.func() == a) // true
const b = new Test();
console.log(b.func() == b) // true
// 2. 返回非对象
function Test(){
this.func = function(){return this}
return 1;
}
const res = Test(); // res = 1;
const a = new Test();
console.log(a.func() == a) // true
const b = new Test();
console.log(b.func() == b) // true
// 3. 返回对象
const obj = {};
function Test(){
this.func = function(){return this}
return obj;
}
const a = new Test();
console.log(a == obj)// new Test()时新建的对象,this指向被丢弃
4、使用call和apply调用时,this就是指定的那个对象
apply 和 call :可以显式的指定函数的上下文,this指向
function test(){
var res = 0;
for(var i = 0; i<argumentes.length; i++){
res += argumengts[i]
}
this.res = res;
}
var obj = {};
var obj2 = {};
test.apply(obj,[1,2,3]); // obj.res = 6
test.call(obj2,1,2,3); // obj2 = 6;
5、bind创建新函数
创建新函数,并绑定到bind方法传入的参数中,新函数被绑定到指定的对象上
function Test(){
this.func = function(){
return this;
}.bind(this) //在new的时候已经确定这个this值为obj
}
var obj = new Test();
var obj2 = {
func : obj.func
}
//obj.func() = obj;
//obj2.func() = obj
6、在全局作用域中this代表window
7、箭头函数中的this
1、箭头函数中的this是定义函数的时候绑定,而不是在执行函数的时候绑定。
2、箭头函数中,this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。
3、箭头函数中的this是在定义函数的时候绑定的
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);
}
}
4、所谓的定义时候绑定,就是this是继承自夫执行上下文的this,比如这里的箭头函数中的this.x,箭头函数本身与say平级以key:value的形式,也就是箭头函数本身所在的对象为obj,而obj的父执行上下文就是window,因此这里的this.x实际上表示的是window.x,因此输出的是11.
var obj={
birth:1990,
getAge:function(){
var b=this.birth;//1990
var fn=()=>new Date().getFullYear()-this.birth;//this指向obj对象
return fn();
}
};
obj.getAge();//32
5、例子中箭头函数本身是在getAge方法中定义,因此,getAge方法的父执行上下文是obj,因此这里的this指向则为obj对象
8、定时器 setInterval setTimeout 里面回调函数的this指向window
var name = 'window';
var obj = {
name: 'obj',
fn: function () {
var timer = null;
clearInterval(timer);
timer = setInterval(function () {
console.log(this.name); //window
}, 1000)
}
}