this关键字
this的涵义
1.this就是属性或方法“当前”所在的对象
var person = {
name: '张三',
describe: function () {
return '姓名:'+ this.name; //因为这个this是在person对象中的describe方法中调用的,所以this指代person,this.name==person.name
}
};
2.this的指向是可变的
var A = {
name: '张三',
describe: function () {
return '姓名:'+ this.name;
}
};
var B = {
name: '李四'
};
B.describe = A.describe; // A里面的属性赋值给B
B.describe() //此时是在B对象的大环境中调用的describe方法,所以this指向B。name='李四'
3.this的动态指向
function f() {
return '姓名:'+ this.name; //定义一个函数返回name
}
var A = {
name: '张三',
describe: f //将函数赋值给describe方法
};
var B = {
name: '李四',
describe: f //将函数赋值给describe方法
};
A.describe() // 在A的环境中调用describe,所以this指向A ,"姓名:张三"
B.describe() // 在B的环境中调用describe,所以this指向B "姓名:李四"
同一个this在不同环境中调用,指向的对象不同。只要函数被赋给另一个变量,this的指向就会发生变化。
this的使用环境
1) 全局环境使用this,它指向的就是顶层对象window
function f() {
console.log(this === window);
}
f() // 此时是在全局环境中调用的函数,所以this指向window
2)构造函数中的this,指的是实例对象。
3)如果对象的方法里面包含this,this的指向就是方法运行时所在的对象。
绑定this的方法
1)call方法
var obj = {};
var f = function () {
return this;
};
f() === window // true
f.call(obj) === obj // call方法改变this指向
call方法的参数,应该是一个对象。如果参数为空、null
和undefined
,则默认传入全局对象。
var n = 123; //全局变量
var obj = { n: 456 };
function a() {
console.log(this.n);
}
a.call() // 123 参数为空默认传入全局对象
a.call(null) // 123 参数为null,默认传入全局对象
a.call(undefined) // 123 参数为undefined,默认传入全局对象
a.call(window) // 123
a.call(obj) // 456
2)apply方法
同样改变this指向,再调用函数。apply是接收数组作为执行时的参数4
function f(x, y){
console.log(x + y);
}
f.apply(null, [1, 1]) // 2
3)bind方法
bind方法用于将函数体内的this绑定到某个对象,然后返回一个新函数。
var d = new Date();
d.getTime()
var print = d.getTime;
print() // Uncaught TypeError: this is not a Date object. 赋给变量`print`以后,内部的this已经不指向Date对象的实例了。
Javascript闭包
闭包就是能够读取外层函数内部变量的函数,闭包一定是两个函数
变量作用域
变量作用域分为两种,全局作用域和局部作用域
1)函数内部可以读取全局变量
2)函数外部无法读取函数内部的局部变量
读取函数内部的局部变量
1)在函数内部再定义一个函数
function f1() {
let code = 200;
function f2() {
console.log(code); //闭包函数,
}
}
2)为外部程序提供访问函数局部变量的入口
function f1() {
let code = 200;
function f2() {
console.log(code);
}
return f2;
}
f1()(); // 200
JS宏任务和微任务
1)js是单线程的,但是分同步异步
同步:同步任务就是指在主线程上排队执行的任务,只有前一个任务执行完毕,才能继续执行下一个任务
异步:异步任务是指不进入主线程,而进入任务队列的任务,只有任务队列通知主线程,某个异步任务可以执行了,该任务才会进入主线程,
2)微任务和宏任务皆为异步任务,它们都属于一个队列
3)宏任务一般是:script、setTimeout、setInterval、postMessage
4)微任务:Promise.then
5)先执行同步再执行异步,异步遇到微任务,先执行微任务,执行完后如果没有微任务,就执行下一个宏任务,如果有微任务,就按顺序一个一个执行微任务
同步,异步微任务,宏任务案例:
console.log(1) //1.执行同步代码,输出1
setTimeout(function() { //异步宏任务,放入宏任务队列
console.log(2) //5.执行同步代码,输出2
new Promise(function(resolve) {
console.log(3) //6.执行同步代码,输出3
resolve()
}).then(function() {
console.log(4) //7.执行异步微任务,输出4
})
})
new Promise(function(resolve) {
console.log(5) //2.执行同步代码,输出5
resolve()
}).then(function() {
console.log(6) //异步微任务,放入微任务队列 4.执行微任务,输出6
})
setTimeout(function() { //异步宏任务,放入宏任务队列
console.log(7) //8.执行同步代码,输出7
new Promise(function(resolve) {
console.log(8) //9.执行同步代码,输出8
resolve()
}).then(function() {
console.log(9) //10.执行异步微任务,输出9
})
})
console.log(10) 3.执行同步代码,输出10
结果:1,5,10,6,2,3,4,7,8,9