vue源碼學習:Object.defineProperty 對數組監聽

上一篇中,咱們介紹了一下defineProperty 對對象的監聽,這一篇咱們看下defineProperty 對數組的監聽前端

數組的變化
先讓咱們瞭解下Object.defineProperty()對數組變化的跟蹤狀況:segmentfault

var a={};
bValue=1;
Object.defineProperty(a,"b",{
    set:function(value){
        bValue=value;
        console.log("setted");
    },
    get:function(){
        return bValue;
    }
});
a.b;//1
a.b=[];//setted
a.b=[1,2,3];//setted
a.b[1]=10;//無輸出
a.b.push(4);//無輸出
a.b.length=5;//無輸出
a.b;//[1,10,3,4,undefined];

能夠看到,當a.b被設置爲數組後,只要不是從新賦值一個新的數組對象,任何對數組內部的修改都不會觸發setter方法的執行。這一點很是重要,由於基於Object.defineProperty()方法的現代前端框架實現的數據雙向綁定也一樣沒法識別這樣的數組變化。所以第一點,若是想要觸發數據雙向綁定,咱們不要使用arr[1]=newValue;這樣的語句來實現;第二點,框架也提供了許多方法來實現數組的雙向綁定。
對於框架如何實現數組變化的監測,大多數狀況下,框架會重寫Array.prototype.push方法,並生成一個新的數組賦值給數據,這樣數據雙向綁定就會觸發。數組

實現簡單的對數組的變化的監聽緩存

var arrayPush = {};

(function(method){
    var original = Array.prototype[method];
    arrayPush[method] = function() {
        // this 指向可經過下面的測試看出
        console.log(this);
        return original.apply(this, arguments)
    };
})('push');

var testPush = [];
testPush.__proto__ = arrayPush;
// 經過輸出,能夠看出上面所述 this 指向的是 testPush
// []
testPush.push(1);
// [1]
testPush.push(2);

在官方文檔,所需監視的只有 push()、pop()、shift()、unshift()、splice()、sort()、reverse() 7 種方法。咱們能夠遍歷一下:前端框架

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

;[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
].forEach(function(item){
    Object.defineProperty(arrayMethods,item,{
        value:function mutator(){
            //緩存原生方法,以後調用
            console.log('array被訪問');
            var original = arrayProto[item]    
            var args = Array.from(arguments)
        original.apply(this,args)
            // console.log(this);
        },
    })
})

完整代碼app

function Observer(data){
    this.data = data;
    this.walk(data);
}

var p = Observer.prototype;

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

;[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
].forEach(function(item){
    Object.defineProperty(arrayMethods,item,{
        value:function mutator(){
            //緩存原生方法,以後調用
            console.log('array被訪問');
            var original = arrayProto[item]    
            var args = Array.from(arguments)
        original.apply(this,args)
            // console.log(this);
        },
    })
})

p.walk = function(obj){
    var value;
    for(var key in obj){
        // 經過 hasOwnProperty 過濾掉一個對象自己擁有的屬性 
        if(obj.hasOwnProperty(key)){
            value = obj[key];
            // 遞歸調用 循環全部對象出來
            if(typeof value === 'object'){
                if (Array.isArray(value)) {
                    var augment = value.__proto__ ? protoAugment : copyAugment  
                    augment(value, arrayMethods, key)
                    observeArray(value)
                }
                new Observer(value);
            }
            this.convert(key, value);
        }
    }
};

p.convert = function(key, value){
    Object.defineProperty(this.data, key, {
        enumerable: true,
        configurable: true,
        get: function(){
            console.log(key + '被訪問');
            return value;
        },
        set: function(newVal){
            console.log(key + '被修改,新' + key + '=' + newVal);
            if(newVal === value) return ;
            value = newVal;
        }
    })
}; 

var data = {
    user: {
        // name: 'zhangsan',
        age: function(){console.log(1)}
    },
    apg: [{'a': 'b'},2,3]
}

function observeArray (items) {
    for (var i = 0, l = items.length; i < l; i++) {
        observe(items[i])
    }
}

//數據重複Observer
function observe(value){
    if(typeof(value) != 'object' ) return;
    var ob = new Observer(value)
      return ob;
}

//輔助方法
function def (obj, key, val) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: true,
    writable: true,
    configurable: true
  })
}

// 兼容不支持__proto__的方法
//從新賦值Array的__proto__屬性
function protoAugment (target,src) {
  target.__proto__ = src
}
//不支持__proto__的直接修改相關屬性方法
function copyAugment (target, src, keys) {
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i]
    def(target, key, src[key])
  }
}


var app = new Observer(data);

// data.apg[2] = 111;
data.apg.push(5);
// data.apg[0].a = 10;
// console.log(data.apg);
相關文章
相關標籤/搜索