Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Last active April 26, 2017 18:45
Show Gist options
  • Save kopylovvlad/37a9af19a8c655e9bdf5da2d02480a60 to your computer and use it in GitHub Desktop.
Save kopylovvlad/37a9af19a8c655e9bdf5da2d02480a60 to your computer and use it in GitHub Desktop.
// object
let obj = {
foo: 'bar'
}
let bazStr = 'baz'
obj[bazStr] = (x, y) => {
return x + y
}
console.log(obj.baz(2, 3)) // 5
console.log('----------')
// class
class User {
foo () {
return 'foo'
}
}
['hello', 'hi', 'bye'].forEach(str => {
User.prototype[`say_${str}`] = () => {
return `${str}`
}
})
let u = new User()
console.log(u.foo()) // foo
console.log(u.say_hello()) // hello
console.log(u.say_hi()) // hi
console.log(u.say_bye()) // bye
console.log('----------')
// monkey patching
class Dollar {
constructor (value) {
this.value = parseInt(value)
}
printValue () {
return `$${this.value}`
}
}
global['Dollar'] = Dollar
class Euro {
constructor (value) {
this.value = parseInt(value)
}
printValue () {
return `€${this.value}`
}
}
global['Euro'] = Euro
class Rouble {
constructor (value) {
this.value = parseInt(value)
}
printValue () {
return `₽${this.value}`
}
}
global['Rouble'] = Rouble
for (let someСlass of [Rouble, Euro, Dollar]) {
String.prototype[`to_${someСlass.name.toLowerCase()}s`] = function () {
return new global[someСlass.name](this.toString())
}
}
console.log('11'.to_euros()) // Euro { value: 11 }
console.log('12'.to_dollars()) // Dollar { value: 12 }
console.log('13'.to_roubles()) // Rouble { value: 13 }
console.log('15'.to_euros().printValue()) // €15
console.log('16'.to_dollars().printValue()) // $16
console.log('17'.to_roubles().printValue()) // ₽17
console.log('----------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment