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

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

“無法訪問未初始化的變量。” 在類構造函數中

“無法訪問未初始化的變量。” 在類構造函數中

牧羊人nacy 2021-12-02 15:30:22
我的 Javascript 代碼中有兩個非常簡單的類:class Renderable{    toHTML(){        return '';    }}class Intro extends Renderable{    constructor(title, pretitle, backgroundImage){        debugger;        this.title = title;        this.pretitle = pretitle;        this.backgroundImage = backgroundImage;    }    [...]}代碼是這樣有序的,所以不應該有任何提升問題。但是,當我加載網頁時,出現以下錯誤:ReferenceError: Cannot access uninitialized variable.在this.title = title;構造函數中的那一行。當我打開調試器時,我看到this確實是undefined. 我究竟做錯了什么?
查看完整描述

2 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

您需要super()在您的子類中調用,正如MDN 解釋的那樣:“在構造函數中使用時, super 關鍵字單獨出現并且必須在使用this 關鍵字之前使用?!?/p>


class Renderable{

    toHTML(){

        return '';

    }

}



class Intro extends Renderable{

    constructor(title, pretitle, backgroundImage){

        super()

        this.title = title;

        this.pretitle = pretitle;

        this.backgroundImage = backgroundImage;

    }

}

const intro = new Intro('title', 'pretitle', 'bg.jpg')

alert(intro.title)


查看完整回答
反對 回復 2021-12-02
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

只需添加這一行


class Intro extends Renderable{

    constructor(title, pretitle, backgroundImage){

        super(); // Whenever you extend a class you have to call parent constructor first

        this.title = title;

        this.pretitle = pretitle;

        this.backgroundImage = backgroundImage;

    }

    [...]

}

根據MDN,在構造函數中使用時, super 關鍵字單獨出現并且必須在使用 this 關鍵字之前使用。super 關鍵字還可用于調用父對象上的函數。你可以閱讀這篇文章,以獲得更好的想法。


查看完整回答
反對 回復 2021-12-02
  • 2 回答
  • 0 關注
  • 860 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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