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…