Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 类内引用变量_Javascript_Ecmascript 6_Class Variables - Fatal编程技术网

Javascript 类内引用变量

Javascript 类内引用变量,javascript,ecmascript-6,class-variables,Javascript,Ecmascript 6,Class Variables,我是一个使用javascript的新手/来自PHP世界/所以我不知道。 我无法访问此。\在fetchPartial()中设置target变量,我看不出我做错了什么 我的错误是TypeError:undefined不是对象(评估“this.\u target”) 你能帮我吗 'use strict'; class View { constructor(partial, target) { this._partial = partial this._targ

我是一个使用javascript的新手/来自PHP世界/所以我不知道。 我无法访问
此。\在
fetchPartial()
中设置target
变量,我看不出我做错了什么

我的错误是
TypeError:undefined不是对象(评估“this.\u 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(){
获取(此._部分)。然后(函数(响应){
//API调用成功!
返回response.text();
}).then(函数(html){
让elem=document.querySelector(this.\u target)//错误:TypeError:undefined不是对象(正在计算'this.\u target')
elem.innerHTML=html
}).catch(函数(err){
//有一个错误
console.warn('出了问题',呃);
});
}
你应该做:

fetchPartial(){
获取(此._部分)。然后(函数(响应){
//API调用成功!
返回response.text();
})。然后((html)=>{
让elem=document.querySelector(this.\u target)//错误:TypeError:undefined不是对象(正在计算'this.\u target')
elem.innerHTML=html
}).catch(函数(err){
//有一个错误
console.warn('出了问题',呃);
});
}

使用

谢谢,现在可以使用了