vue data不可以使用箭头函数的问题解析

这篇文章主要介绍了vue data不可以使用箭头函数问题,本文通过源码解析给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

首先需要明确,a() {}和 b: () => {}是不同的

 

1

2

3

4

5

6

let obj = {

   a() {},

   // 相当于

   a:function() {},

   b: () => {}

}

1 VUE.js 源码解析

注意此处只设计核心代码

这段代码也是UMD实现原理,本文这里不是重点,有兴趣的可以自行探究。

 

1

2

3

4

5

6

7

8

(function (global, factory) {

   typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :

   typeof define === 'function' && define.amd ? define(factory) :

   (global.Vue = factory());

  }(this, (function (){

   'use strict';

    console.log(this) //*undefined*

  })))

解析一:

对于javascript来说,非严格模式下函数都会有一个this指向,不清楚的这里有传送门this指向相关

说一下本文中涉及的this指向问题,如果不是严格模式,this应该指向window,但是由于vue作者使用的是严格模式,所以他指向了undefined

以下是vue中data的实现原理

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

(function (global, factory) {

  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :

  typeof define === 'function' && define.amd ? define(factory) :

  (global.Vue = factory());

 }(this, (function (){

  'use strict';

  function getData(data,vm) {

   return data.call(vm, vm)

  }

  function initData(params) {

   data = vm._data = typeof data === 'function'

   ? getData(data, vm)

   : data || {};

  }

  initData() 

 })))

也就是说每次新创建实例的时候都会去判断是否有data函数,如果有的话就会将其赋值给vm._data,心细的同学会发现对于Vmm实例来说是没有data,而是有vm._data

es5函数和es6箭头函数

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

var obj = {

  a: () => {

  'use strict';

   console.log(this,'a')

  },

  b() {

   console.log(this,'b')

  },

  c() {

   // window

   let e = () => {

    console.log(this,'e')

   }

   return e

  }

 }

 obj.a() // window

 obj.b() // obj

 obj.c()() // obj

对于普通函数(非严格模式下),this指向调用者,es6中的this指向声明时的上下文环境。

结合以上两点解析今天的问题

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

(function (global, factory) {

  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :

  typeof define === 'function' && define.amd ? define(factory) :

  (global.Vue = factory());

 }(this, (function (){

  'use strict';

  let vm = {}

  var data = () => {

   console.log(this);//undefined

   return {

    a: 1

   }   

  }

  function getData(data,vm) {

   return data.call(vm, vm)

  }

  function initData(params) {

   data = vm._data = typeof data === 'function'

   ? getData(data, vm)

   : data || {};

  }

  initData()

  console.log(vm);

 })))

以上代码说明你使用箭头函数给data: () => {} this指向undefined的时候,是会赋值给vm._data,但是他会相当于一个全局的,只要你不刷新页面他就会缓存你的data。

如果我们使用data() {}this指向Vm实例,所以他会随着实例更新。

转载https://www.php.cn/js-tutorial-405826.html

原文地址:https://www.cnblogs.com/gopark/p/11444730.html