Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
display() {
return `${this.firstName} ${this.lastName}`;
}
}
class LocationProxy {
constructor() {
this.x = 0;
this.y = 0;
}
get(target, name) {
// Override the `display` method
if (name === 'display') {
return (() => `${target.display()} at ${this.x}, ${this.y}`);
}
// Let other accessors pass through if they exist
if (name in target) {
return target[name];
}
// Provide support for getting the `x` property
if (name === 'x') {
return this.x;
}
// Provide support for getting the `y` property
if (name === 'y') {
return this.y;
}
}
set(target, name, value) {
// Let existing properties pass through
if (name in target) {
target[name] = value;
}
// store `x` on our self LocationProxy
if (name === 'x') {
this.x = value;
}
// store `y` on our self LocationProxy
if (name === 'y') {
this.y = value;
}
}
}
const person = new Person("Ryan", "Cromwell");
const location = new LocationProxy();
const proxiedPerson = new Proxy(person, location);
proxiedPerson.x = 10;
proxiedPerson.y = 20;
console.log();
console.log('*** Regular Person ***');
console.log(person.display());
console.log(person);
console.log();
console.log('*** Person with location support ***');
console.log(proxiedPerson.display());
console.log(proxiedPerson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.