Created
June 6, 2019 02:50
-
-
Save saihoooooooo/7d31afee214fe61c264161589ddd06fb to your computer and use it in GitHub Desktop.
jsの再帰Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function tracePropAccess(obj, setMethod, path) { | |
path = path || []; | |
return new Proxy(obj, { | |
get: function(target, propKey, receiver) { | |
var temp = Reflect.get(target, propKey, receiver); | |
if (temp && typeof temp === 'object') { | |
return tracePropAccess(temp, setMethod, path.concat(propKey)); | |
} else { | |
return temp; | |
} | |
}, | |
set: setMethod | |
}); | |
} | |
var persons = { | |
'a': { | |
firstName: 'alfred', | |
lastName: 'john', | |
inner: { | |
momonga: 8250 | |
} | |
}, | |
'b': { | |
firstName: 'unko', | |
lastName: 'chinko', | |
inner: { | |
salary: 18250, | |
proffesion: [] | |
} | |
} | |
} | |
var proxyA = tracePropAccess(persons.a, function(target, key, value) { | |
target[key] = value; | |
console.log('Aの内容が変更'); | |
return true; | |
}); | |
var proxyB = tracePropAccess(persons.b, function(target, key, value) { | |
target[key] = value; | |
console.log('Bの内容が変更'); | |
return true; | |
}); | |
proxyA.inner.momonga = 'foo'; | |
proxyB.tName = 'meee'; | |
proxyB.firstName = 'wan'; | |
proxyB.inner.proffesion.push({ hoge: 'fuga' }); | |
proxyB.inner.proffesion[0].hoge = 'piyo'; | |
console.log(persons); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment