亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

引用類內的變量

引用類內的變量

絕地無雙 2023-11-02 21:32:44
我是一個使用 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();
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

代替:


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

? ? ? ? });

? ? }

使用箭頭函數


查看完整回答
反對 回復 2023-11-02
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號