Skip to content

Instantly share code, notes, and snippets.

@morrelinko
Created January 9, 2018 17:47
Show Gist options
  • Save morrelinko/9ad3078475d73c5899d9e3521d1bed9a to your computer and use it in GitHub Desktop.
Save morrelinko/9ad3078475d73c5899d9e3521d1bed9a to your computer and use it in GitHub Desktop.
JS Magic Methods
'use strict'
const assert = require('assert')
module.exports = function (obj) {
return new Proxy(obj, {
get (target, prop, receiver) {
if (prop in target) {
return Reflect.get(target, prop, receiver)
}
if (target.__get) {
return target.__get(prop)
}
},
set (target, prop, value, receiver) {
if (prop in target) {
return Reflect.set(target, prop, value, receiver)
}
if (target.hasOwnProperty('__set')) {
target.__set(prop)
}
return true
}
})
}
@morrelinko
Copy link
Author

morrelinko commented Jan 9, 2018

Example

'use strict'

const magic = require('./magic')

class Request {
  constructor() {
    this.attributes = {}
  }
  
  __get (prop) {
    return this.attributes[prop]
  }
  
  __set (prop, value) {
    this.attributes[prop] = value
  }
}

let re = magic(new Request())

re.user = 'morrelinko'
re.site = 'http://morrelinko.com'

console.log(re.user) // morrelinko
console.log(re.attributes) // { user: 'morrelinko', site: 'http://morrelinko.com' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment