Upgrade to Pro — share decks privately, control downloads, hide ads and more …

クラスへの割り込み処理とProxyとReflect / method-intercept-wi...

クラスへの割り込み処理とProxyとReflect / method-intercept-with-proxy-and-reflect

初投稿です。

hivesbee

May 24, 2019
Tweet

More Decks by hivesbee

Other Decks in Programming

Transcript

  1. ࣮૷ͯ͠Έͨʢࣦഊฤʣ // ׂΓࠐΈॲཧ͞ΕΔ Utility Ϋϥε class _Util { static greet(name)

    { console.log(`hello! ${name}!`) } static throwError(...args) { console.log(‘Sample#throwError') // ͜͜ͰΤϥʔ͕ى͜Δ throw new Error(...args) } } // Proxy ʹΘͨ͢ϋϯυϥ const handler = { get(target, name, receiver) { try { interceptor() return target[name] } catch (e) { onError(e) } } } // ͍ͭ͜ΒΛ export export let interceptor // ׂΓࠐΈॲཧ༻ export let onError // Τϥʔϋϯυϥ export const Util = new Proxy(_Util, handler) // ׂΓࠐΈॲཧͷ࣮૷ interceptor = () => { console.log('intercept!') } onError = (e) => { console.log('onError!') console.log(e) } // ࣮ࡍʹݺͼग़͢ Util.greet('haga') Util.throwError('sample error') 6UJM$MBTTKT #VTJOFTT-PHJDKT উͬͨͳʂ ෩࿊ೖͬͯ͘Δ Χϓʔ
  2. ࣮૷ͯ͠Έͨʢࣦഊฤʣ JOUFSDFQU IFMMPIBHB JOUFSDFQU 4BNQMFUISPX&SSPS 6TFSTʜUFTUKT UISPXOFX&SSPS BSHT  ?

    &SSPSTBNQMFFSSPS BU1SPYZUISPX&SSPS 6TFSTʜUFTUKT  BU0CKFDUBOPOZNPVT 6TFSTʜUFTUKT  ʜ ࣮ߦͨ݁͠Ռʜ ΨνͷΤϥʔൃੜ
 ʢΤϥʔϋϯυϥͰݕ஌͍ͯ͠ͳ͍ʣ ૲ Χϓʔ
  3. ࣮૷ͯ͠Έͨʢࣦഊฤʣ const handler = { get(target, name, receiver) { try

    { interceptor() return target[name] } catch (e) { onError(e) } } } ݪҼ͸ʜ ϝιουͦͷ··ฦͯ͠·͢΍Μʜ
 ͦΓΌಈ͖·ͤΜΘʜ ͱͳΔͱIBOEMFS಺Ͱॲཧͤͯ͋͛͞ͳ͍ͱʜ
 ˠͦ͏͍͑͹3FqFDUͬͯ͋ͬͨͳʜ
  4. ࣮૷ͯ͠Έͨʢ੒ޭʁฤʣ const handler = { get(target, name, receiver) { return

    (...args) => { const apiMethod = Reflect.get(target, name, receiver) const boundApiMethod = apiMethod.bind(target) try { interceptor() return boundApiMethod(...args) } catch (e) { onError(e) } } } } const handler = { get(target, name, receiver) { try { interceptor() return target[name] } catch (e) { onError(e) } } } 3FqFDUHFUͰϝιουΛऔΓग़ͯ͠ॲཧ
 ΤϥʔϋϯυϦϯά·ͰؚΊͨॲཧΛSFUVSO ΍͔ͬͨʁ Χϓʔ #FGPSF "GUFS ˠ;ͭʔʹಈ͍ͨ
  5. ࣮૷ͯ͠Έͨʢ੒ޭฤʣ const handler = { get(target, name, receiver) { return

    (...args) => { try { interceptor() return target[name](...args) } catch (e) { onError(e) } } } } ಈ͍ͨΑʜ
 ʢमਖ਼ͷϓϧϦΫग़͞ͳ͖Όʜʣ ૲ Χϓʔ