JS中的this
普通函数:谁调用(this)就指向谁

function fn() {
console.log("普通函数调用", this);
}
fn();
window.fn();
function Person() {
console.log("构造函数调用", this);
}
var p1 = new Person();
var obj = {
sayHi:function () {
console.log("对象方法调用", this);
}
};
obj.sayHi();
document.onclick = function () {
console.log("事件绑定调用方法" , this);
}
setInterval(function () {
console.log("定时器函数调用", this);
},1000)
箭头函数:调用者指向谁,(this)则指向谁。指向函数声明时所在作用域下的对象,而不是运行时所在的对象。

如何改变this的指向
- 利用call、apply、bind方法
- 通过变量将需要的this存储下来:let _this = this
- 借用其他对象的方法:构造函数、arguments
call、apply、bind函数,区别
const obj = {
a:100
}
function sum(x,y){
console.log(this.a+x+y)
}
sum(3,7)
解析:[直接调用,this指向window,window下没有a属性,window.a = undefined]
sum.call(obj,3,7)
sum.apply(obj,[3,7])
[第一个参数是新的this指向,从第二个参数开始表示函数自身的参数]
[bind是返回对应函数体,便于后面调用]
sum.bind(obj,3,7)()
箭头函数与普通函数的区别
- this指向不同
- 普通函数,内部的this指向函数运行时所在的对象
- 箭头函数没有自己的this对象,内部的this是定义时上层作用域中的this
- 箭头函数是匿名函数,不能使用new操作符
- 箭头函数没有原型属性
什么情况不能使用箭头函数?
function Test(name,age){
this.name = name
this.age = age
}
let fn = new Test('tom',12)
console.log(fn.name)
const Test2 = (name,age)=>{
this.anme = name
this.age = age
}
let fn2 = new Test2('lina',12)
console.log(fn2.name)
dom.addEventListener('click',()=>{
console.log('this',this)
})
let obj = {
key:'key',
getKey:()=>{
return this.key
}
getKey2(){
return this.key
}
}
obj.getKey();
obj.getKey2();
let obj = {
key:'key'
}
obj._proto_getKey =()=>{
console.log('this',this)
return this.key
}
obj.getKey()
- Vue的生命周期及methods中的方法不建议使用箭头函数:this指向的是window对象