js中this的指向问题
参考:https://blog.csdn.net/chen_junfeng/article/details/109235442
1. 在全局作用域中
=>this -> window
全局环境中,this 默认绑定到window。
<script> console.log(this); //this->window </script>
2. 在普通函数中
=>this取决于谁调用,谁调用我,this就指向谁,跟如何定义无关
var obj = {
fn1:function() {
console.log(this);
},
fn2:function(){
fn3()
}
}
function fn3() {
console.log(this);
}
fn3(); // this->window
obj.fn1(); // this->obj
obj.fn2(); // this->window 3. 箭头函数中的this
箭头函数没有自己的 this,箭头函数的 this 就是上下文中定义的 this,因为箭头函数没有自己的 this 所以不能用做构造函数。
var div = document.querySelector('div');
var o = {
a:function(){
var arr = [1];
// 就是定义所在对象中的this
// 这里的 this —> o
arr.forEach(item = >{
// 所以this -> o
console.log(this);
})
},
// 这里的 this 指向 window, o 是定义在 window 中的对象
b:()=>{
console.log(this);
},
c:function() {
console.log(this);
}
}
div.addEventListener('click', item=>{
console.log(this);//this->window 这里的this就是定义上文window环境中的this
});
o.a(); //this->o
o.b();//this->window
o.c();//this->o 普通函数谁调用就指向谁 4. 定时器中的this
定时器中的 this->window,因为定时器中采用回调函数作为处理函数,而回调函数的 this->window
setInterval(function() {
console.log(this); //this->window
},500)
setTimeout(function() {
console.log(this); //this->window
},500) 5. 事件绑定中的this
事件源.onclik = function(){ } //this -> 事件源
事件源.addEventListener(function(){ }) //this->事件源
var div = document.querySelector('div');
div.addEventListener('click',function() {
console.log(this); //this->div
});
div.onclick = function() {
console.log(this) //this->div
} 6. 构造函数中的this
构造函数配合 new 使用, 而 new 关键字会将构造函数中的 this 指向实例化对象,所以构造函数中的 this->实例化对象
new关键字会在内部发生什么
// 第一行,创建一个空对象obj。
var obj ={};
// 第二行,将这个空对象的 __proto__ 成员指向了构造函数对象的 prototype 成员对象.
obj.__proto__ = CO.prototype;
// 第三行,将构造函数的作用域赋给新对象,因此 CO 函数中的 this 指向新对象 obj,然后再调用 CO 函数。于是我们就给 obj 对象赋值了一个成员变量p,这个成员变量的值是” I’min constructed object”。
CO.call(obj);
// 第四行,返回新对象obj。
return obj; function Person(name,age) {
this.name = name;
this.age = age;
}
var person1 = new Person();
person1.name = 'andy';
person1.age = 18;
console.log(person1);//Person {name: "andy", age: 18}
var person2 = new Person();
person2.name = 'huni';
person2.age = 20;
console.log(person2);// Person {name: "huni", age: 20} 
京公网安备 11010502036488号