vue2对数组覆盖7个方法源码解析

以下是源码 并添加解析,源码路径src\core\observer\array.js

/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

import { def } from "../util/index";
// 获取原型
const arrayProto = Array.prototype;
// 克隆副本
export const arrayMethods = Object.create(arrayProto);

// 覆盖7个原型方法
const methodsToPatch = [
  "push",
  "pop",
  "shift",
  "unshift",
  "splice",
  "sort",
  "reverse",
];

/**
 * Intercept mutating methods and emit events
 */
// 遍历覆盖
methodsToPatch.forEach(function (method) {
  // cache original method
  const original = arrayProto[method];
  // 覆盖方法
  def(arrayMethods, method, function mutator(...args) {
    // 先执行原始方法
    const result = original.apply(this, args);
    // 扩展:变更通知
    const ob = this.__ob__;
    // 插入元素操作
    let inserted;
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
        break;
    }
    // 对插入操作进行响应绑定
    if (inserted) ob.observeArray(inserted);
    // notify change
    // 变更通知
    ob.dep.notify();
    return result;
  });
});

源码引入的def方法在源码 src\core\util\lang.js路径下:

export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

你可能感兴趣的:(vue源码解析,vue2,vue.js)