首先,我们直接console.log(this);毫无疑问,全局环境下指向的是window
ok,但是,我们一般使用this是在方法里面,就像下面这样,输出:我的名字是miao
对象的方法中的this,this指向调用他的对象
let cat = {
name:'miao',
age:12,
ayName(){
console.log('我的名字是'+this.name);
}
}
cat.sayName()
在函数里面使用this,这里的函数是全局函数,所以调用就像是window.fun()
function fun(){
console.log(this);
}
fun()
我们在html中定义一个按钮,然后为这个按钮添加一个点击事件,会输出这个按钮,所以事件中的this指向触发事件的DOM元素
<button>按钮</button>
<script>
let btn = document.querySelector('button')
btn.onclick=function(){
console.log(this);
},
</script>
然后,我们再看构造函数,我们一般使用构造函数就是 定义一个名字 = new 构造函数()
构造函数的this,里面的this指向new关键字创建出来的实例对象
function Fun(){
this.name = '小明'
}
let f = new Fun()
console.log(f);
最后看一下箭头函数,箭头函数没有this,外面指向谁,里面就指向谁,或者说在哪里定义就指向谁,下面这个输出cat对象
let cat = {
name:'miao',
sayName(){
setTimeout(()=>{
console.log(this);
},1000)
}
}
cat.sayName()
ok,这就是我对this的理解