面试题答案
一键面试function observable(data) {
const subscribers = [];
function subscribe(callback) {
subscribers.push(callback);
return () => {
const index = subscribers.indexOf(callback);
if (index !== -1) {
subscribers.splice(index, 1);
}
};
}
function notify(property, value) {
subscribers.forEach(callback => callback(property, value));
}
const handler = {
get(target, prop) {
if (prop ==='subscribe') {
return subscribe;
}
const value = target[prop];
if (typeof value === 'object' && value!== null) {
return observable(value);
}
return value;
},
set(target, prop, value) {
const oldValue = target[prop];
target[prop] = value;
if (oldValue!== value) {
notify(prop, value);
}
return true;
}
};
return new Proxy(data, handler);
}
你可以使用以下方式测试这个函数:
const myData = {
name: 'John',
age: 30,
address: {
city: 'New York'
}
};
const myObservable = observable(myData);
const unsubscribe = myObservable.subscribe((prop, value) => {
console.log(`${prop} has changed to ${value}`);
});
myObservable.name = 'Jane';
myObservable.address.city = 'Los Angeles';
unsubscribe();