Skip to content
Advertisement

Javascript – How do I have a get/set in a method? (e.g. pineapple.is_a.fruit)

I have an assignment where I’m supposed to make magic out of programming. I’m unable to find any answers online, as I do not know the search term for it (tried method in a method etc…). Appreciate any help given!

Here’s what I got: I need to create a class that builds upon itself. e.g.

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

I do not even know where to begin. My attempt is similar to this, but I’m getting undefined.

class Thing {
  constructor(type) {
    this.type = type;
  }
  
  is_a(bool) {
    this.fruit = this.is_a(bool);
  }
}

Advertisement

Answer

Assuming that they can be defined in advance, in order to have sub-properties like pineapple.is_a.fruit, you’ll need to define objects on the object’s is_a and is properties. For instance (see comments):

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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement