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

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

Javascript - 如何在方法中獲取/設置?(例如菠蘿.is_a.fruit)

Javascript - 如何在方法中獲取/設置?(例如菠蘿.is_a.fruit)

肥皂起泡泡 2023-07-06 16:35:40
我有一項任務,要求我通過編程創造奇跡。我無法在網上找到任何答案,因為我不知道它的搜索詞(嘗試過方法中的方法等...)。感謝所提供的任何幫助!這就是我得到的:我需要創建一個基于自身構建的類。例如const pineapple = new Item('pineapple');pineapple.type = fruit // this is simplepineapple.is_a.fruit = true // this I do not knowpineapple.is.heavy = true // same thing我什至不知道從哪里開始。我的嘗試與此類似,但我變得不確定。class Thing {  constructor(type) {    this.type = type;  }    is_a(bool) {    this.fruit = this.is_a(bool);  }}
查看完整描述

1 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

假設它們可以提前定義,為了擁有像 的子屬性pineapple.is_a.fruit,您需要在對象的is_a和is屬性上定義對象。例如(見評論):


class Item { // `Item` rather than `Thing`, right?

    constructor(type) {

        this.type = type;

        // Create an `is_a` property that's an object with a `fruit` property

        this.is_a = {

            fruit: false // Or whatever the initial value should be

        };

        // Create an `is` property that's an object with a `heavy` property

        this.is = {

            heavy: false // Or whatever the initial value should be

        };

    }

}


const pineapple = new Item('pineapple');

pineapple.type = "fruit"; // I added quotes here


console.log("is_a.fruit before:", pineapple.is_a.fruit);

console.log("is.heavy before:", pineapple.is_a.fruit);


pineapple.is_a.fruit = true;

pineapple.is.heavy = true;


console.log("is_a.fruit after: ", pineapple.is_a.fruit);

console.log("is.heavy after: ", pineapple.is_a.fruit);


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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