Javascript - 如何在方法中获取/设置?(例如菠萝.is_a.fruit)

我有一项任务,要求我通过编程创造奇迹。我无法在网上找到任何答案,因为我不知道它的搜索词(尝试过方法中的方法等...)。感谢所提供的任何帮助!


这就是我得到的:我需要创建一个基于自身构建的类。例如


const pineapple = new Item('pineapple');

pineapple.type = fruit // this is simple


pineapple.is_a.fruit = true // this I do not know

pineapple.is.heavy = true // same thing


我什至不知道从哪里开始。我的尝试与此类似,但我变得不确定。


class Thing {

  constructor(type) {

    this.type = type;

  }

  

  is_a(bool) {

    this.fruit = this.is_a(bool);

  }

}


肥皂起泡泡
浏览 126回答 1
1回答

蛊毒传说

假设它们可以提前定义,为了拥有像 的子属性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 hereconsole.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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript