Javascript 类内引用变量
我是一个使用javascript的新手/来自PHP世界/所以我不知道。 我无法访问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
此。\在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('出了问题',呃);
});
}
使用谢谢,现在可以使用了