Skip to content

Instantly share code, notes, and snippets.

@mfdeveloper
Last active January 1, 2021 16:58
Show Gist options
  • Save mfdeveloper/edb249ccdaeecaa9586c2fddb391907f to your computer and use it in GitHub Desktop.
Save mfdeveloper/edb249ccdaeecaa9586c2fddb391907f to your computer and use it in GitHub Desktop.
This is a example of a dynamic class method on Typescript. Until here, is not possible access class properties inside the overrided/new method
/**
* Typescript dynamic class method example
*
* REFERENCES:
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html
* @see https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Mixins.md
* @see http://blog.brillskills.com/2013/09/exploring-javascript-prototypes-via-typescripts-class-pattern
* @see https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript
*
* For this example, using IONIC 2/3 Toast component to override a method
*
* `To test`
*
* 1) Install ionic-cli first whit `npm install -g ionic@latest`
* 2) Create a new application that use `ionic-angular` like dependency with:
* `ionic start myApp blank|sidemenu|tabs`
* 3) Open app.component.ts file and copy/paste the code below on topo of this file
* 4) Try use ToastController to create a toast with a closeButton:
*/
import { ToastCmp } from 'ionic-angular/components/toast/toast-component';
// PROBLEM: The "this" context is changed when do a copy.
const cbClick = ToastCmp.prototype.cbClick.bind(ToastCmp.prototype);
// Override original method
ToastCmp.prototype['click'] = function() {
console.log('TESTE!!');
}
ToastCmp.prototype.cbClick = function() {
if (typeof ToastCmp.prototype['click'] === 'function') {
ToastCmp.prototype['click']();
} else {
cbClick();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment