微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue中的普通函数与箭头函数以及this关键字

普通函数

普通函数指的是用function定义的函数

var hello = function () {
    console.log("Hello, Fundebug!");
}

箭头函数

箭头函数指的是用=>定义的函数

var hello = () => {
    console.log("Hello, Fundebug!");
}

箭头函数没有自己的this值,箭头函数中所使用的this来自于函数作用域链。

this

this就是代码执行时当前的context object。

The JavaScript context object in which the current code is executing.

Global context

代码没有在任何函数中执行,而是在全局作用域中执行时,this的值就是global对象,对于浏览器来说,this就是window。

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

Function context

函数中的this值取决于这个函数是怎样被调用

Inside a function, the value of this depends on how the function is called.

axios中this的指向问题

在vue中使用axios做网络请求的时候,会遇到this不指向vue,而为undefined。
解决办法:使用箭头函数 "=>"
"=>" 内部的this是词法作用域,由上下文确定(也就是由外层调用者vue来确定)。

methods: {
      loginAction(formName) {
        this.$axios.post("……")
          .then(function(response){
               console.log(this); //这里 this = undefined
          })
          .catch((error)=> {
              console.log(this); //箭头函数"=>"使this指向vue
          });

        });
      }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐