概述

我们知道,Vuejs通过Object.defineProperty来对对象的属性进行改造,但是我有一个疑问,就是原来对象的那个数据属性去哪里了呢!

解答

其实,这个Object.definePropertyapi不仅可以为对象定义属性,也可以用来修改属性。也就是说,其实Vuejs就是将对象原有的数据属性,改造成了访问器属性。
举个🌰:

  1. var obj = {};
  2. //为obj对象声明一个数据属性a。
  3. obj.a = 1;
  4. console.log(Object.getOwnPropertyDescriptor(obj, a));
  5. //{value: 1, writable: true, enumerable: true, configurable: true}
  6. //将a属性改造成访问器属性
  7. Object.defineProperty(obj, 'a', {get() {return 1}})
  8. //再次查看属性的描述符
  9. console.log(Object.getOwnPropertyDescriptor(obj, a));
  10. //{set: undefined, enumerable: true, configurable: true, get: ƒ}

所以实际上Vuejs是将数据属性改造成了访问器属性。