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))
core/index.js
// 两层意思,1 个Vue.挂个静态成员FunctionalRenderContext function Vue () { } function FunctionalRenderContext () { console.log('hello world') } Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }) FunctionalRenderContext.prototype = { _o:function () { console.log('o is:o') }, _k: function () { console.log('k is: k') } } // Vue.FunctionalRenderContext(); var o = new Vue.FunctionalRenderContext() o._o()