【问题标题】:referencing variable inside class [duplicate]在类中引用变量[重复]
【发布时间】:2021-03-21 05:35:06
【问题描述】:

我是一个使用 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();

【问题讨论】:

    标签: javascript ecmascript-6 class-variables


    【解决方案1】:

    代替:

    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

    【讨论】:

    • 谢谢,现在可以使用了
    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多