observe源码

1. oberver/array.js

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

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

const arrayProto = Array.prototype
const arrayMethods = Object.create(arrayProto)

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]
  console.log('methods:', method)
  def(arrayMethods, method, function mutator (...args) {
    const result = original.apply(this, args)
    console.log('this:=', this)
    console.log('args=:', args)
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    return result
  })
})
const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
var arr1 = [1, 3, 4, 9]
arr1.__proto__ = arrayMethods
console.log('arr1=', arr1.slice(2))

  

猜你喜欢

转载自www.cnblogs.com/liuyinlei/p/11132900.html