共计 995 个字符,预计需要花费 3 分钟才能阅读完成。
var Dep = {
target: null
};
function defineComputed(obj, key, computeFunc) {
computeFunc = computeFunc.bind(obj);
Dep.target = computeFunc;
var 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…