JavaScript this
this 是什么
this 是 JavaScript 的一个关键字,在函数内部使用,表示"当前执行上下文所属的对象"。它不写死在定义处,而是由调用方式决定:谁调用它,this 就指向谁。
全局环境中的 this
在浏览器全局作用域中,this 指向全局对象 window:
console.log(this === window); // 输出:true
var a = 1;
console.log(this.a); // 输出:1(等价于 window.a)
普通函数中的 this
非严格模式下,普通函数里的 this 指向 window;严格模式下是 undefined:
function show() {
return this;
}
console.log(show() === window); // 浏览器中输出:true
对象方法中的 this
方法(定义在对象里的函数)由对象调用时,this 指向该对象;单独取出调用时 this 又会变:
var person = {
name: "小明",
sayHi: function () {
return "你好,我是" + this.name;
}
};
console.log(person.sayHi()); // 输出:你好,我是小明
var fn = person.sayHi; // 把函数单独取出来
console.log(fn()); // this 变成 window,取不到 name
// 输出:你好,我是undefined
事件处理中的 this
给元素绑定的事件处理函数里,this 指向触发事件的元素:
<button id="btn">点击我变蓝</button>
<script>
document.getElementById("btn").onclick = function () {
this.style.color = "blue"; // this 就是按钮元素本身
};
</script>
效果:点击按钮后,按钮文字变成蓝色。
用 call / apply / bind 指定 this
想让某函数"以指定对象为 this"来执行,可以用这三个方法:
function greet(city) {
return this.name + " 住在 " + city;
}
var user = { name: "小红" };
console.log(greet.call(user, "上海")); // 输出:小红 住在 上海
console.log(greet.apply(user, ["北京"])); // 输出:小红 住在 北京
var bindGreet = greet.bind(user, "广州");
console.log(bindGreet()); // 输出:小红 住在 广州
区别:call 与 apply 立即执行(apply 参数用数组),bind 返回新函数,可稍后再调用。
箭头函数没有自己的 this
箭头函数不绑定 this,它会继承外层作用域的 this,常用于回调场景:
var counter = {
count: 0,
start: function () {
setInterval(() => {
this.count++; // 箭头函数继承 start 的 this(counter)
}, 1000);
}
};
counter.start();
若这里写成普通 function,this 会指向 window 导致 count 加不上去,箭头函数正好解决这个问题。
小结
记住一句话:this 指向谁,看"谁调用了它"。全局里指向 window、方法里指向所属对象、事件里指向触发元素;需要手动指定 this 时用 call/apply/bind,需要继承外层 this 时用箭头函数。