js中3种常见的this场景
- 普通函数
var name = 'ian';
function getName() {
console.log(this.name); //ian
}
普通的函数的this指向window
- 对象中的函数
var userInfo = {
name: 'Tom',
getName: function() {
console.log(this.name);
}
}
userInfo.getName(); //Tom
var _getName = userInfo.getName;
_getName(); //undefined
对象中函数的this指向对象本身
- 构造函数
function Cat(name) {
this.name = name;
}
var tom = new Cat('Tom'); // {name:'Tom'}
在使用构造器的时候会返回一个对象,构造函数中的this就是指向这个对象
特殊的箭头函数
上面说过this通常是指向函数的调用者,但箭头函数的this指向的是词法作用域
var name = 'jack'
var userInfo = {
name: "tom",
getName: () => {
console.log(this.name);
}
}
userInfo.getName(); //jack
箭头函数被提升到全局window下,箭头函数所处的上下文就是window,会在window下面寻找name属性。现在来看下面稍微复杂一些的例子:
var name = 'jack'
var userInfo = {
name: "tom",
getName: function() {
console.log(this.name); //tom
//普通函数
var foo = function() {
console.log(this.name); //jack
}
//箭头函数
var bar = () => {
console.log(this.name); //tom
}
foo();
bar();
}
}
userInfo.getName();
this丢失问题
有些时候我们想在函数里面执行回调函数的函数,通常会丢失掉this,例如下面这个场景,callBack函数中的this指向了window而不是button元素。
<button type="button" id='btn'>按钮</button>
document.getElementById('btn').onclick=function(){
console.log(this);
function callBack(){
console.log('callback函数执行',this)//window
}
callBack();
}
这种情况要通过箭头函数或者call、apply、bind函数来修正this
- 通过箭头函数修正this
<button type="button" id='btn'>按钮</button>
document.getElementById('btn').onclick=function(){
console.log(this); //<button type="button" id="btn">按钮</button>
var callBack=()=>{
console.log('callback函数执行',this);//<button type="button" id="btn">按钮</button>
}
callBack();
}
- 通过apply函数修正this
<button type="button" id='btn'>按钮</button>
document.getElementById('btn').onclick=function(){
console.log(this); //<button type="button" id="btn">按钮</button>
function callBack(){
console.log('callback函数执行',this);//<button type="button" id="btn">按钮</button>
}
callBack.call(this);
}
总结:
- JavaScript中的this是动态的,它总是指向函数的直接调用者。
- 箭头函数的this指向的是词法作用域
- 可以通过call、apply方法修正this指向