1

I an a newbie working with javascript / came from the PHP world / so pardom my ignorance. I can't access this._target variable inside a fetchPartial() and I can't see what I am doing wrong.

My error is TypeError: undefined is not an object (evaluating 'this._target')

Can you help me pelase?

'use strict';

class View {
    constructor(partial, target) {
        this._partial = partial
        this._target = target;
    }
    
    fetchPartial() {
        fetch(this._partial).then(function (response) {
            // The API call was successful!
            return response.text();
        }).then(function (html) {
            let elem = document.querySelector( this._target ) // error: TypeError: undefined is not an object (evaluating 'this._target')
            elem.innerHTML = html
        }).catch(function (err) {
            // There was an error
            console.warn('Something went wrong.', err);
        });
    }
}

let p = new View('/_partial.html', '#_partial');
p.fetchPartial();

1 Answers1

1

Instead of:

fetchPartial() {
        fetch(this._partial).then(function (response) {
            // The API call was successful!
            return response.text();
        }).then(function (html) {
            let elem = document.querySelector( this._target ) // error: TypeError: undefined is not an object (evaluating 'this._target')
            elem.innerHTML = html
        }).catch(function (err) {
            // There was an error
            console.warn('Something went wrong.', err);
        });
    }

You should do:

fetchPartial() {
        fetch(this._partial).then(function (response) {
            // The API call was successful!
            return response.text();
        }).then((html) => {
            let elem = document.querySelector( this._target ) // error: TypeError: undefined is not an object (evaluating 'this._target')
            elem.innerHTML = html
        }).catch(function (err) {
            // There was an error
            console.warn('Something went wrong.', err);
        });
    }

Use an arrow function

Andres Gardiol
  • 1,312
  • 15
  • 22