Reactivity: Object.defineProperty and Observer

Explore Vue 2 reactivity through defineReactive, Observer, and array method interception.

🎯 Introduction

Change data, and the page updates automatically: this is one of Vue 2's defining behaviors. In this article, we open that black box. By the end, you will be able to:

  • Explain how Object.defineProperty intercepts data reads and writes.
  • Describe the roles of defineReactive, Observer, and array method interception.
  • Build a small reactivity system that logs data reads and changes.
  • Recognize two familiar Vue 2 reactivity limitations and use Vue.set to address them.

The source excerpts use Vue 2.7.16 from the GitHub vuejs/vue repository, focusing on src/core/observer/index.js and src/core/observer/array.js. Run the examples directly with Node.js v22.


🧱 What Is Reactivity?

Reactivity means that when data changes, the places that use it update automatically.

Think of a newspaper subscription. You register with the publisher (dependency tracking), and whenever a new issue appears (a data change), it is delivered to you (an update). You do not need to ask the publisher every day whether there is anything new.

In Vue 2, the publisher is the data declared in data. Vue transforms it so that reads register who uses it, and writes notify those users to update. Object.defineProperty provides this registration and notification mechanism.

If you have taken the Vue 2 course, recall how changing an input updates fields declared in data and immediately changes the page. This mechanism makes that possible.


🧱 Reviewing Object.defineProperty

Object.defineProperty can define a getter and setter for an object property. Reads invoke the getter, and writes invoke the setter, allowing us to insert our own logic.

Start with this runnable example:

demo.js
const user = {};
let name = 'noxussj';

Object.defineProperty(user, 'name', {
    get() {
        console.log('Read name');
        return name;
    },
    set(newVal) {
        console.log('Changed name:', newVal);
        name = newVal;
    },
});

user.name; // Logs: Read name
user.name = 'Alex'; // Logs: Changed name: Alex

Run node demo.js with Node.js v22 to see both reads and writes being intercepted.

The actual data lives in the local variable name; user.name is only an access point. The getter and setter retain access to that variable through a closure, so both reads and writes use the correct value.

Intercepting reads and writes gives us the foundation for reactivity: register users in the getter (dependency tracking), and notify them in the setter.


🧱 defineReactive: Make One Property Reactive

Vue 2 wraps the process of adding a getter and setter to a property in defineReactive. This teaching version omits Flow annotations and edge cases while preserving the core logic:

// Simplified from defineReactive in src/core/observer/index.js
function defineReactive(obj, key, val) {
    // Recursively make nested objects reactive
    observe(val);

    Object.defineProperty(obj, key, {
        get() {
            // Track dependencies: register who uses this property
            // Placeholder for dep.depend(); details follow in the next article
            return val;
        },
        set(newVal) {
            if (newVal === val) return;
            val = newVal;
            // Make newly assigned objects reactive too
            observe(newVal);
            // Trigger an update; view notifications are covered in the next article
            // dep.notify()
            console.log(`Update triggered: ${key} changed to`, newVal);
        },
    });
}

Notice three points:

  • Recursive observation: observe(val) makes nested properties such as user.info.name reactive too.
  • Track dependencies in get: record whoever reads the property during rendering. The next article explains dependency tracking and Watcher in detail.
  • Trigger updates in set: notify the view when the value changes. Observe the new value too, so newly assigned objects do not escape observation.

🧱 Observer: Walk the Entire Object

defineReactive handles one key at a time, but data is usually a whole object. Observer walks its keys and calls defineReactive for each one:

// Simplified from Observer in src/core/observer/index.js
class Observer {
    constructor(data) {
        // Mark data with __ob__ to avoid observing it again
        Object.defineProperty(data, '__ob__', {
            value: this,
            enumerable: false, // Exclude the marker from enumeration
        });

        if (Array.isArray(data)) {
            // Arrays need special handling, covered next
            protoAugment(data, arrayMethods);
            this.observeArray(data);
        } else {
            // Objects: make each property reactive
            this.walk(data);
        }
    }

    walk(data) {
        Object.keys(data).forEach((key) => {
            defineReactive(data, key, data[key]);
        });
    }

    observeArray(items) {
        items.forEach((item) => observe(item));
    }
}

function observe(data) {
    if (typeof data !== 'object' || data === null) return;
    // Reuse the existing observer when __ob__ is present
    if (data.__ob__) return data.__ob__;
    return new Observer(data);
}

The __ob__ property matters for two reasons:

  • Observation marker: its presence shows that data has already been observed, avoiding redundant getter/setter setup.
  • enumerable: false: excludes __ob__ from Object.keys and for...in, and from subsequent recursive observation, keeping it out of application data traversal and avoiding recursive cycles.

After observe processes an object, its nested properties have getters and setters. Reads track dependencies and writes trigger updates, completing object reactivity.


🧱 Special Handling for Arrays: Override Seven Methods

Objects can be intercepted key by key with defineReactive. Arrays need a different approach: adding getters and setters to thousands of indices would be expensive, with limited benefit for the array update patterns this design targets.

Vue 2 instead intercepts mutating methods such as push and splice, which cover common array changes. It creates an object that inherits from the array prototype, overrides seven mutating methods on it, and uses that object as the reactive array's prototype:

// Simplified from src/core/observer/array.js
const arrayProto = Array.prototype;
// Create an object that inherits from the array prototype
const arrayMethods = Object.create(arrayProto);

// Seven methods that mutate the original array
const methodsToPatch = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'];

methodsToPatch.forEach((method) => {
    const original = arrayProto[method];

    arrayMethods[method] = function (...args) {
        // 1. Call the original method to preserve array behavior
        const result = original.apply(this, args);

        // 2. Observe elements inserted by push, unshift, or splice
        let inserted;
        if (method === 'push' || method === 'unshift') {
            inserted = args;
        } else if (method === 'splice') {
            inserted = args.slice(2); // splice inserts elements from its third argument onward
        }
        if (inserted) {
            inserted.forEach((item) => observe(item));
        }

        // 3. Notify the view (a placeholder until the next article)
        // ob.dep.notify()
        console.log('Array changed; update triggered');
        return result;
    };
});

// Set the reactive array's prototype to arrayMethods
function protoAugment(data, proto) {
    Object.setPrototypeOf(data, proto);
}

An ordinary array has the prototype chain array -> Array.prototype. After this change, it becomes array -> arrayMethods -> Array.prototype. A call to list.push() resolves to the override on arrayMethods, which wraps the original method on Array.prototype with interception logic.

This provides two capabilities:

  • Intercept mutations: list.push(4) triggers an update because push has been overridden.
  • Observe inserted elements: an object inserted with push is processed by observe, so later changes to its properties also trigger updates.

Array behavior stays intact: list.length and for loops work as usual. The prototype chain simply gains an extra interception layer.


⚠️ Two Familiar Limitations

The defineProperty approach has a fundamental limitation: it can only intercept keys for which accessors have already been defined. This leads to two common pitfalls.

Limitation 1: Adding Object Properties Does Not Trigger Updates

data() {
    return {
        user: { name: 'noxussj' },
    };
},
mounted() {
    // user has no age property, so adding it does not trigger an update
    this.user.age = 18;
},

walk only traverses existing keys during initialization. The later age property has no getter or setter, so Vue cannot detect its changes.

Use Vue.set (or this.$set inside a component) to make the new property reactive and trigger an update:

this.$set(this.user, 'age', 18);

Limitation 2: Assigning Array Indices or Changing length Does Not Trigger Updates

// Neither operation triggers an update
this.list[0] = 'new value';
this.list.length = 0;

As described above, Vue does not intercept individual array indices for performance reasons. Direct assignment bypasses the interception logic, and changing length does not invoke any of the seven overridden methods.

Use $set or the overridden splice method instead:

this.$set(this.list, 0, 'new value');
// Or
this.list.splice(0, 1, 'new value');

// Empty the array
this.list.splice(0);
These limitations often explain why data changes while the view stays unchanged. For new properties and array index assignments, use this.$set or splice. Vue 3's reactivity system uses Proxy, removing these two limitations.

❓ Knowledge Check

Q1: Why does Vue 2 avoid intercepting array indices?

Primarily for performance. Arrays may contain hundreds or thousands of elements, making accessor setup expensive. Overriding seven mutating methods covers most array updates without that per-index cost.

Q2: Why is __ob__ non-enumerable?

An enumerable marker would appear in Object.keys and for...in, mixing internal metadata into application data traversal. Recursive observation could also encounter it again and enter a cycle. With enumerable: false, it remains accessible as a marker without appearing in enumeration.

Q3: Can changing a property of an object inserted with push trigger an update?

Yes. The overridden push observes inserted elements, giving the new object's properties getters and setters. Later property changes can therefore trigger updates.

Q4: How does Vue 3 remove these limitations?

Vue 3 uses Proxy instead of Object.defineProperty. A proxy intercepts operations on the object as a whole, including new properties, array index assignments, and length changes.


🧪 Exercise

Without looking up the solution, complete these two functions to build a small reactivity system. Log “Read xxx” when a property is read and “xxx changed to: new value” when it changes. Save it as a .js file and run it with Node.js v22.

function defineReactive(obj, key, val) {
    // Write your code here
}

function observe(obj) {
    // Write your code here (hint: iterate over every key in obj)
}

const data = { name: 'noxussj', age: 18 };
observe(data);

// Expected output:
// Read name
// name changed to: Alex
// Read age
console.log(data.name);
data.name = 'Alex';
console.log(data.age);

For an extra challenge, add a nested object to data, such as info: { city: 'London' }. Can your implementation log accesses to data.info.city too? What needs to change?


🎉 You now understand the core of Vue 2 reactivity! Next, we will explore dependency tracking and Watcher: how Vue records who uses each property and routes updates to the relevant parts of the view.