引用类内的变量

我是一个使用 javascript 的新手/来自 PHP 世界/所以请原谅我的无知。我无法访问this._targeta 中的变量fetchPartial(),也看不到我做错了什么。


我的错误是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();


绝地无双
浏览 116回答 1
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);        });    }使用箭头函数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript