Javascript - 如何在方法中使用 get/set? (例如 pineapple.is_a.fruit)
Javascript - How do I have a get/set in a method? (e.g. pineapple.is_a.fruit)
我有一项任务,我应该通过编程创造奇迹。
我无法在网上找到任何答案,因为我不知道它的搜索词(方法中的尝试方法等...)。感谢您提供的任何帮助!
这是我得到的:
我需要创建一个基于自身的 class。
例如
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);
}
}
假设它们可以提前定义,为了让sub-properties像pineapple.is_a.fruit
,你需要在对象的is_a
和[=13=上定义对象] 特性。例如(见评论):
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);
我有一项任务,我应该通过编程创造奇迹。 我无法在网上找到任何答案,因为我不知道它的搜索词(方法中的尝试方法等...)。感谢您提供的任何帮助!
这是我得到的: 我需要创建一个基于自身的 class。 例如
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);
}
}
假设它们可以提前定义,为了让sub-properties像pineapple.is_a.fruit
,你需要在对象的is_a
和[=13=上定义对象] 特性。例如(见评论):
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);