Created
August 5, 2017 07:37
-
-
Save honda0510/cd6917b98647a8ceb0d916b3187e11ad to your computer and use it in GitHub Desktop.
JavaScript: プロパティへの値代入時の処理を変更する
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 Greeter { | |
constructor(private _greeting: string) { | |
} | |
get greeting() { | |
return this._greeting; | |
} | |
set greeting(value: string) { | |
this._greeting = value; | |
} | |
} | |
let greeter = new Greeter("Hello, world"); | |
const prop = 'greeting'; | |
const real = Object.getOwnPropertyDescriptor(Greeter.prototype, prop); | |
console.log(real); | |
Object.defineProperty(greeter, prop, { | |
get: () => real.get(), | |
set: value => { | |
real.set(value); | |
console.log('success'); | |
}, | |
enumerable: real.enumerable, | |
configurable: real.configurable | |
}); | |
let button = document.createElement('button'); | |
button.textContent = "Say Hello"; | |
button.onclick = function () { | |
greeter.greeting = 'test'; | |
alert(greeter.greeting); | |
} | |
document.body.appendChild(button); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment