返回

透过this理解ES5中函数的调用机制

见解分享

this的指向规则剖析

在ES5中,this的指向始终由函数的直接调用者决定 ,而不是由函数的定义方式或所属对象决定。为了理解这一规则,我们通过几个例子进行剖析。

例1:全局函数

function fun1() {
  console.log(this);
}

fun1();

在例1中,fun1是定义在全局作用域的函数,没有所属对象,直接调用fun1()等同于调用window.fun1(),因此this指向window对象。

例2:对象方法

const person = {
  name: 'John',
  sayName: function() {
    console.log(this.name);
  }
};

person.sayName();

在例2中,sayName是定义在person对象上的方法,直接调用person.sayName()时,this指向person对象,因为person是sayName的直接调用者。

例3:构造函数

function Person(name) {
  this.name = name;
  this.sayName = function() {
    console.log(this.name);
  };
}

const person1 = new Person('John');
person1.sayName();

在例3中,Person是一个构造函数,直接调用new Person('John')时,this指向新创建的person1对象,因为person1是构造函数Person的直接调用者。

箭头函数的特殊性

ES6引入了箭头函数(=>) ,箭头函数的this绑定机制与传统函数不同。箭头函数的this由其所在的作用域决定 ,而不是由函数的调用方式决定。这使得箭头函数在某些场景下非常有用。

例4:箭头函数

const person = {
  name: 'John',
  sayName: () => {
    console.log(this.name);
  }
};

person.sayName();

在例4中,sayName是一个箭头函数,直接调用person.sayName()时,this指向person对象,因为箭头函数的this由其所在的作用域决定,而person.sayName()的作用域是person对象。

箭头函数的this绑定机制使得箭头函数非常适合作为回调函数使用 。因为箭头函数的this不会被调用方式所影响,因此可以保证箭头函数在回调函数中始终指向正确的作用域。

结论

通过本文的剖析,我们可以看到,在ES5中,this的指向始终由函数的直接调用者决定,箭头函数作为ES6的新特性,改变了this的绑定机制,使得箭头函数的this由其所在的作用域决定。理解this的指向规则对于编写高质量的JavaScript代码非常重要。