In Vue2. X, Object.defineProperty() is the core of the reactive principle.

Static methods object.defineProperty (obj, prop, Descriptor), which can precisely control the behavior of attributes by defining their metadata information. In simple terms, you can add or remove attribute values to an object.

Object. DefineProperty (obj, prop, descriptor) parameter

  • obj

    Object an Object on which attributes must be defined.
  • prop

    String | Symbol, it must be, to define or modify the name of the property.
  • descriptor

    Object, the property descriptor that must be defined or modified.

Return value: Object, which returns the Object obj passed to the function.

Attribute descriptors are divided into numeric descriptors and access descriptors

(1) Both data descriptor and access descriptor have the following key values:

The property descriptor of this property can be modified again, and the property can be deleted without any additional control system, if and only if the property is true, works freely and freely. The default is false.

* Enumerable: A property can appear in an object’s enumerable property if and only if its Enumerable is true. The default is false.

(2) Optional key value of data descriptor:

Value: indicates the initial value of the attribute. It can be any valid JavaScript value (numeric value, object, function, etc.). The default is undefined.

Writable: This property can be written to a value only if its writable is true. The default is false.

(3) Optional keys of access descriptor:

Get: A method that provides a getter for a property, undefined if there is no getter. When the property is accessed, the method is executed with no arguments, but with this object (which is not necessarily the object defining the property because of inheritance). The default is undefined.

Set: a method that provides a setter for a property, otherwise undefined. This method is triggered when the property value is modified. This method takes a unique parameter, the new parameter value for the property. The default is undefined.

Code sample

(1) Create a property

<script> const Obj = {}; Object. DefineProperty (Obj, "a", {value: 100, default: 1) Writable: true, // Enumerable: // The property descriptor can be modified again, and works without any additional control system. // Obj has property A, which is 1 console.log(obj.a) // output: 1 </script>Copy the code

(2) Get and set access descriptors

const Obj = {}; let v = null; Object.defineProperty(Obj, 'a', { get: function () { return v; }, set: function (newValue) { v = newValue; }}); Obj.a = 1000; console.log(Obj.a); // Output: 1, indicating that the getter and setter for attribute A are in effectCopy the code