class 中的引用变量

referencing variable inside class

我是 javascript 的新手 / 来自 PHP 世界 / 请原谅我的无知。 我无法访问 fetchPartial() 中的 this._target 变量,我看不出我做错了什么。

我的错误是TypeError: undefined is not an object (evaluating 'this._target')

你能帮我解决一下吗?

'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();

而不是:

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);
        });
    }

你应该这样做:

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);
        });
    }

使用 arrow function