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.
JavaScript
x
7
1
const pineapple = new Item('pineapple');
2
pineapple.type = fruit // this is simple
3
4
pineapple.is_a.fruit = true // this I do not know
5
pineapple.is.heavy = true // same thing
6
7
I do not even know where to begin. My attempt is similar to this, but I’m getting undefined.
JavaScript
1
10
10
1
class Thing {
2
constructor(type) {
3
this.type = type;
4
}
5
6
is_a(bool) {
7
this.fruit = this.is_a(bool);
8
}
9
}
10
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):
JavaScript
1
25
25
1
class Item { // `Item` rather than `Thing`, right?
2
constructor(type) {
3
this.type = type;
4
// Create an `is_a` property that's an object with a `fruit` property
5
this.is_a = {
6
fruit: false // Or whatever the initial value should be
7
};
8
// Create an `is` property that's an object with a `heavy` property
9
this.is = {
10
heavy: false // Or whatever the initial value should be
11
};
12
}
13
}
14
15
const pineapple = new Item('pineapple');
16
pineapple.type = "fruit"; // I added quotes here
17
18
console.log("is_a.fruit before:", pineapple.is_a.fruit);
19
console.log("is.heavy before:", pineapple.is_a.fruit);
20
21
pineapple.is_a.fruit = true;
22
pineapple.is.heavy = true;
23
24
console.log("is_a.fruit after: ", pineapple.is_a.fruit);
25
console.log("is.heavy after: ", pineapple.is_a.fruit);