let context = {a: 1, b:2, c:3, d:4};
console.log(JSON.stringify(getDependencies(context, (context) => {
if (context.a) {
return context.b;
} else {
return context.c;
}
})));
/*
希望返回 {
value: 2
dependencies: ['a', 'b']
}
*/
function getDependencies(context, callback) {
//实现
let dependencies = [];
let value;
function observe(data, key, value) {
let check = {};
Object.defineProperty(data, key, {
get() {
if (!check[key]) {
dependencies.push(key);
check[key] = true;
}
return value;
},
set(newVal) {
if (newVal !== value) {
value = newVal;
}
}
})
}
Object.keys(context).forEach((key) => {
observe(context, key, context[key]);
});
value = callback(context);
return {value, dependencies}
}
console