vue 箭头函数与function函数的区别

1、this指向问题:

(1)funtion普通函数中this指向window;所以如果需要在function函数中使用this对象,需要事先把this对象赋值给其他变量,如:

let self = this;
 this.getReportId().then(function(result) {
    self.id = result;
    alert(self.id);
 });

(2)箭头函数中this指向vue实例:箭头函数相当于匿名函数,并且简化了函数定义。看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。此时this在箭头函数中已经按照词法作用域绑定了。很明显,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例了。如:

this.getReportId().then(result => {
        this.id = result;
        alert( this.id);
});

2、写法转换:以下两种写法效果是一样的:

formatter: function(params) {
                  return params.name +  已接入:  + params.data.num[2];
              }
formatter: params => {
            return params.name +  已接入:  + params.data.num[2];
          }
经验分享 程序员 微信小程序 职场和发展