上一篇关于 call()、apply() 和 bind() 方法的介绍中说明了:这三个方法都是重定义 this 的,所以在这里有必要总结一下 this ~
this 就是一个指针,指向调用函数的对象。
在javascript中,this 的值不是固定不变的,而是由运行时的环境决定的,在不同的环境中,this指代的值也不同。
方法中
在方法中,this 指向的是调用这个方法的对象。
let stu = {
name: "Jake",
sex : "male",
age : 15,
sayInfo : function() {
return this.name + " " + this.sex;
}
};
console.log(stu.sayInfo());
运行结果:
Jake male
在这个方法中,this 指向的是 stu 对象。
全局环境中
全局环境中使用 this 时,this 指向 window 全局对象。
console.log(window === this);
let name = "jfghd";
console.log(window.name);
this.sname = "bhgj";
console.log(window.sname);
console.log(sname);
运行结果:
true
kj
bhgj
bhgj
函数中
1)默认情况下:
在函数中,默认情况下,this 指向全局对象。
function myFun(str){
this.name = str;
}
myFun("jkl");
console.log(name);
运行结果:
jkl
2)严格模式下:
在函数中,严格模式下,函数没有被绑定到 this 上,这时候,this 是 undefined。
"use strict";
function myFun(){
return this;
}
console.log(myFun());
运行结果:
undefined
事件中
在HTML 事件中,this 指向接收事件的 HTML 元素。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button onclick="this.style.background='red'">点击变色</button>
</body>
</html>
运行效果:
这个例子中,click事件是 button 接收的,this 指向按钮元素。
对象方法中
在对象方法中,this 指向的是该对象。
let obj = {
firstName : "John",
lastName : "Doe",
age : 16,
myFunc : function() {
return this;
}
};
console.log(obj.myFunc());
运行结果:
{firstName: "John", lastName: "Doe", age: 16, myFunc: ƒ}
在这个例子中, this 是在对象方法中,this 指向的是 obj 这个对象。
let stu = {
firstName: "Jake",
lastName : "Joson",
age : 16,
stuName : function() {
return this.firstName + " " + this.lastName;
}
};
console.log(stu.stuName());
运行结果:
Jake Joson
调用对象中的方法,this 指向 stu 对象。
显示函数绑定
let stu1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
let stu2 = {
firstName:"John",
lastName: "Doe",
}
let obj = stu1.fullName.call(stu2);
console.log(obj);
运行结果:
John Doe
当在对象上面使用了函数对象方法 apply 和 call 时,则会改变 this 的指向,在上面这个例子中,调用 stu1.fullName. 方法,传入参数 stu2 时,this 本来应该是指向 stu1 ,结果却指向了 stu2,这是因为显示函数绑定的作用。
new运算符
当通过 new 调用函数时,函数被当作一个构造函数,this 指向构造函数创建的对象;
function myFun(){
this.name = "ghfo";
}
let obj = new myFun();
console.log(obj.name);
运行结果:
ghfo
内部函数中
在内部函数中,this 指向全局对象 window。
var name = "kj";
let obj = {
name : "John",
myFunc : function() {
var test = function(){
console.log(this.name);
}
test();
}
};
obj.myFunc();
运行结果:
kj
但是,在内部函数中,如果将 this 作为变量保存下来,则 this 指向该对象。
var name = "kj";
let obj = {
name : "John",
myFunc : function() {
var sfj = this;
var test = function(){
console.log(sfj.name);
}
test();
}
};
obj.myFunc();
运行结果:
John