1、this
指向要素
-
this
指向的只可能是对象 -
this
指向谁取决于函数在哪调用 -
this
指向的对象称为函数上下文,也叫函数的调用者
2、指向规律
方法中,this指向该方法的所属对象,如果单独使用,this表示全局对象;在函数中也是表示全局对象,但是在严格模式下,this是未定义的;在事件中则是接收事件的元素;类似call() 和 apply() 方法可以将 this 引用到任何对象
2.1 函数名()直接调用
this指向window
function func(){
console.log(this);
}
func();
运行结果:
2.2 方法中调用this
在对象方法中,this
指向调用它所在方法中的对象
var person = {
firstName: "123",
lastName: "456",
myFunction: function () {
return this.firstName + " " + this.lastName;;
}
};
console.log(person.myFunction());
运行结果:
2.3 单独使用this
此时指向全局对象
var a=this;
console.log(this);
运行结果:
2.4 函数中使用this
- 默认情况下
this
指向全局对象
function func() {
return this;
}
console.log(func());
运行结果:
- 严格模式下
this
显示未定义
"use strict";
function func() {
return this;
}
console.log(func());
运行结果:
2.5 对象方法中绑定
this
指向了person对象
var person = {
firstName: "123",
lastName: "456",
id: 1234,
myFunction: function () {
return this;
}
};
console.log(person.myFunction());
运行结果:
2.6 显式函数绑定
js
中函数也是对象,对象就有方法,apply
和call
就是函数对象的方法,他们允许切换函数执行的上下文环境,这种情况就被称为this
绑定函数
var person1 = {
FullName: function () {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName: "A",
lastName: "B"
}
console.log(person1.FullName.call(person2));
运行结果:
3、箭头函数的this
指向
- 箭头函数本身没有作用域(无this)
- 基本语法:参数=>函数体
- this等同于上一层非箭头函数的this值或全局对象(window或undefined)
参考资料:this关键字