Daniel Mizerski Daniel Mizerski - 1 year ago 153
TypeScript Question

Typescript private method "is not a function"

I probably missunderstood some concept, but after reading 4 topics on stackoverflow, and documentation for "private members in typescript" - I am still confused.

I am writing simple mouse IO (first typescript project). This is full code of malfunctioning mouse class:

class Mouse {
public left: MouseKeyData = new MouseKeyData();
public right: MouseKeyData = new MouseKeyData();
public whell: MouseKeyData = new MouseKeyData();

public x: number = 0;
public y: number = 0;

private crossBrowserButton(e: any):string {
switch (e.button) {
case 0: return 'left';
case 1: return 'whell';
case 2: return 'right';
case 3: return 'back';
case 4: return 'forward';
return 'none';

private onMouseDown(e: any):void {
let target: MouseKeyData = this.left;
try {console.log(this.crossBrowserButton(e))} catch (a) {console.warn(a)} finally {}
if(target) {

private onMouseUp(e: any):void {
let target: MouseKeyData = this.left;
if(target) {

private onMouseMove(e: any): void {
this.x = e.pageX;
this.y = e.pageY;

public constructor() {
let anchor = document.body;

anchor.addEventListener('mousedown', this.onMouseDown);
anchor.addEventListener('mouseup', this.onMouseUp);
anchor.addEventListener('mousemove', this.onMouseMove);


I used to call
, but I got only
this.crossBrowserButton is not a function(…)

I think I lost
scope some-where, but
works perfectly.

Thanks in advance!

Answer Source

Sounds like you did the exact opposite of what you should have done. In your original code there is a problem with the execution scope of your event listeners. They are not bound to the scope of the class and will therefore execute in the context they are run from.

Your event binding should look like this.

    anchor.addEventListener('mousedown', this.onMouseDown.bind(this));
    anchor.addEventListener('mouseup', this.onMouseUp.bind(this));
    anchor.addEventListener('mousemove', this.onMouseMove.bind(this));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download