「这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战」
前言
掘友们好,我是cv竹叶,函数方法中this
的指向经常让人晕头转向,这次我们就来理解理解this
吧!
this的理解
在JavaScript中,this
的指向是调用时决定的,而不是创建时决定的,简单来说,this
具有运行期绑定的特性。
this的调用位置
this
调用位置应该是当前正在执行的函数的前一个调用中。例如:
function baz(){
console.log("baz");
bar();
}
function bar(){
console.log("bar");
}
baz();
顺序调用是baz()→bar(),this
调用位置是正在执行的函数bar()的前一个baz()调用中。
this的全局上下文
在浏览器里面this等价于window对象,如果你声明一些全局变量,这些变量都会作为this的属性。
console.log(window === this); // true
this的函数上下文
直接调用的函数,this
指向全局
function foo(){
return this;
}
console.log(foo() === window); // true
通过call()、apply()、bind()
可以改变this指向,就像前面说的this
具有运行期绑定的特性。
var cat = {
name: "咪咪",
};
function say(job){
console.log(this.name);
}
say.call(cat,"FE"); // 咪咪
say.apply(cat,["FE"]); // 咪咪
var f = say.bind(cat);
console.log(f());//指向f对象去
箭头函数的this
所有的箭头函数都没有自己的this,都指向外层上下文的this值
function cat(name){
this.name = name;
this.say = () => {
var name = "黑猫";
return this.name;
}
}
var person = new cat("咪咪");
console.log(cat.say()); // 咪咪,而不是黑猫
一个DOM事件处理函数的this
this指向触发事件的元素,也就是始事件处理程序所绑定到的DOM节点。
var dom = document.getElementById("id");
dom.addEventListener("click",function(e){
console.log(this);
console.log(this === e.target); // true
})
HTML标签内联事件处理函数
this指向所在的DOM元素
<button onclick="console.log(this);">点击</button>
结言
我们只要了解this的概念和其调用位置,就可以知道this的指向了!如果有帮助到你,就点个赞吧!