Skip to content

[vue] 在vue项目中如果methods的方法用箭头函数定义结果会怎么样? #475

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] 在vue项目中如果methods的方法用箭头函数定义结果会怎么样?

Activity

yin-pathfinder

yin-pathfinder commented on Jun 28, 2019

@yin-pathfinder

this为undefined

shanyanwt

shanyanwt commented on Jul 2, 2019

@shanyanwt

因为箭头函数默绑定父级作用域的上下文,所以不会绑定vue实例,所以 this 是undefind

Hellohanlili

Hellohanlili commented on Jul 3, 2019

@Hellohanlili

会使this指向的结果返回undefined

weipxiu

weipxiu commented on Jul 4, 2019

@weipxiu

this指向的是当前方法,并不会报错

Janesummers

Janesummers commented on Jul 23, 2019

@Janesummers

this指向实例最开始实例化的那个作用域

binnuo

binnuo commented on Jul 30, 2019

@binnuo

var app = nvar app = new Vue({
el: "#app",
data: {},
methods: {
a: () => {
console.log(this); //Window
}
}
});
为什么我的this指向的是Window?

yin-pathfinder

yin-pathfinder commented on Aug 8, 2019

@yin-pathfinder

var app = nvar app = new Vue({
el: "#app",
data: {},
methods: {
a: () => {
console.log(this); //Window
}
}
});
为什么我的this指向的是Window?

虽然没有尝试过,但是我估计你是在html里面直接用<script>引入vue的,this的默认绑定在window上,而我是用的webpack构建的,默认在严格模式下,this默认绑定为undefined

censek

censek commented on Oct 15, 2019

@censek
data() {
    return {
      log: "111"
    };
  },
methods: {
    test: () => {
      console.log(this.log); //undefined
    }
}
data() {
    return {
      log: "111"
    };
  },
methods: {
    test() {
      console.log(this.log); //111
    }
}
nannan0109

nannan0109 commented on Oct 21, 2019

@nannan0109

我的this为什么不是undefined

Hemumu5460

Hemumu5460 commented on May 22, 2020

@Hemumu5460

在严格模式下this是undefined,在非严格模式下指向window

Good-XiaAo

Good-XiaAo commented on Aug 4, 2021

@Good-XiaAo

问一些没用的问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@yin-pathfinder@nannan0109@Hellohanlili@Janesummers

        Issue actions

          [vue] 在vue项目中如果methods的方法用箭头函数定义结果会怎么样? · Issue #475 · haizlin/fe-interview