this指向:
1、构造函数的this指向实例化对象
2、普通函数和匿名函数的this指向window
3、在对象中,函数this指向当前对象
4、在数组中,函数this指向当前数组
5、在定时器函数中this指向window
6、箭头函数中的this指向其父作用域
1、构造函数的this指向实例化对象
/* 构造函数中的this指向 */
function CreateFunction(name,age){
this.name = name;
this.age = age;
console.log(this);
}
let fn = new CreateFunction('小明',18)
console.log(fn);
这里出现了一个新的关键字new,new关键字在啊这里的作用是:
(1)创建一个空对象
(2)让构造函数的this指向实例化对象
第二点作用就解释了为什么构造函数中的this会指向实例化对象的问题。
2、普通函数和匿名函数的this指向window
/* 普通函数的this指向 */
function fn(){
console.log(this);
}
/* 匿名函数的this指向 */
(function(){
console.log(this);
})()
3、在对象中,函数的this指向当前对象
/* 在对象中,函数的this指向 */
var obj = {
name: "小明",
age: 18,
getName: function () {
console.log(this);
}
}
obj.getName()
4、在数组中,函数的this指向当前数组
/* 在数组中,函数的this指向 */
var arr = [1, 2, function () {
console.log(this);
}]
// 调用数组中函数的方法
console.log(arr[2]());
5、在定时器函数中this指向window
/* 定时器函数中的this指向 */
var timer = setTimeout(function () {
console.log(this);
}, 1000)
console.log(timer);
6、箭头函数中的this是其父作用域的this指向
如果父级程序有this指向,指向向的就是父级程序的this指向
如果父级程序没有this指向(对象,数组是没有this),指向的是window
var obj = {
name: '小明',
getName: () => {
console.log(this);
}
}
obj.getName()
var obj = {
name: '小明',
getName() {
var getAge = () => {
console.log(this);
}
return getAge()
}
}
obj.getName()