对象的盘算属性

var Dep = {
    target: null
};

function defineComputed(obj, key, computeFunc) {
    computeFunc = computeFunc.bind(obj);
    var value;
    Dep.target = function() {
        value = computeFunc();
    };
    value = computeFunc();
    Object.defineProperty(obj, key, {
        get: function() {
            return value;
        },
        set: function() {
            // don't do anything. can't set computed funcs
        }
    })
}
function defineReactive(obj, key, val) {
    // all computed properties that depend on this
    var deps = [];
    
    Object.defineProperty(obj, key, {
        get: function() {
            // Check if there's a computed property which 'invoked'
            // this getter. Also check that it's already not a dependency
            if (Dep.target) {
                // add the dependency
                deps.push(Dep.target);
                Dep.target = null;
            }
            return val;
        },
        set: function(newValue) {
            if (val === newValue) return;
            val = newValue;
            
            // notify all dependent computed properties
            deps.forEach(func => func());
        }
    })
}

var obj = {};
defineReactive(obj, 'a', 0);
defineReactive(obj, 'c', 10);
defineComputed(obj, 'b', function() {
    console.log(1);
    return this.a + this.c;
});


obj.a += 1;

console.log(obj.b);

obj.a += 1;

console.log(obj.b);

obj.a += 1;

console.log(obj.b);

参考文档:
https://www.cnblogs.com/kidne…
https://skyronic.com/blog/vue…

    原文作者:lisa
    原文地址: https://segmentfault.com/a/1190000018847091
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞