this用法总结

134 阅读1分钟

this表示当前对象的一个引用。 在JavaScriptthis不是固定不变的,它会随着执行环境的改变而改变。

  1. 在普通函数中: this指向window
var a = 'a';
function fun() {
    console.log(this.a);
};
fun.a = 'funa';
fun(); // 'a'
// 注意在严格模式下,普通函数中的this执向undefined
  1. obj.fun: this指向前面的对象
const obj = {
    a: 'a'
};
obj.a  // 'a'
  1. 使用new调用构造函数 this指正在创建的新对象
function Fun() {
    this.a = 'a';
};
const fun1 = new Fun();
fun1.a;  // 'a'
  1. 构造函数原型对象方法中的this: 谁调用this指向谁
function Fun() {
    this.a = 'a';
};
Fun.prototype.speak = function() {
    return this.a
}
const fun1 = new Fun();
fun1.speak()  // 'a'
  1. 事件处理函数中的 this: this指向当前正在触发事件的DOM元素对象
  2. vue2中的this: this指向当前组件实例
  3. 箭头函数中的this: 与箭头函数所处的词法作用域的this相同,也就是箭头函数内部的this与其外部的this保持一致
const obj = {
    a: 'a',
    speak() {
        return () => {
            return this.a;
        }
    }
};
const fun1 = obj.speak();
fun1()  // 'a'
  1. 使用Array.prototype的call、apply、bind方法中的this: this指传入的第一个参数
const obj1 = {
    a: 'a1',
    speak() {
        return this.a;
    }
};
const obj2 = {
    a: 'a2',
};

obj1.speak.call(obj2);  // 'a2'
// 本文在此仅举例,call、apply、bind的用法可自行查阅

总结:判断this的指向,更需要关注运行时所在的上下文环境