Created
January 25, 2018 22:18
-
-
Save cromwellryan/b3d5d057f1e7aaef1eb16f6067d375ff to your computer and use it in GitHub Desktop.
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
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