Inheritance class in different files parent “this” result to undefined

Viewed 119

I'm a newbie in javascript/react and I try to make a class inheritance.

The problem is, when I make a new "Child" and call a function from the parent, "this" result to undefined...

Here is my files :

1st file:

import React, { Component } from 'react';
import ChildChecker from './ChildChecker';

class ExampleForm extends Component {
    render() {
        let Checker = new ChildChecker();
        return (
           <label>
               Name :
                   <input type="text" onBlur={Checker.handleNameBlur} />
           </label>
        )
    }
}

export default ExampleForm;

ChildChecker :

import ParentChecker from './ParentChecker';

export default class ChildChecker extends ParentChecker {
}

ParentChecker :

export default class ParentChecker {
    constructor() {
        this.data = {
            'foo': 'bar',
        };
    }
    handleNameBlur(e) {
        console.log(this.data); // <=== "this" result to undefined.
        /* ... */
    }
}

Thanks

1 Answers

The handleNameBlur is used in another context (Class ExampleForm) so you should bind it in ParentChecker to keep the context.

export default class ParentChecker {
    constructor() {
        this.data = {
            'foo': 'bar',
        };

        this.handleNameBlur = this.handleNameBlur.bind(this);
    }
    handleNameBlur(e) {
        console.log(this.data); // <=== "this" result to undefined.
    /* ... */
    }
}
Related