我有一个 // Create the file where the photo should save.
File file = null;
try {
file = createImageFile();
} catch (IOException e) {
break;
}
// The second parameter is the name of authorities.
Uri uri = FileProvider.getUriForFile(this,
"com.limxtop.research.fileprovider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, fullSizeRequestCode);
类(代表物质宇宙中元素的原子):
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
# path("notification_u/", UserNotificationConsumer),
])
),
"chat-channel":MessageRouter(),
})
有92种天然元素-例如,其中之一就是氧气。我想为每个元素创建一个子类。
Atom
一个正常发生的氧原子为默认数量的中子(8个),但是它可以改变,所以我希望能够创建一个这样的原子:
class Atom {
constructor(neutronCount) {
this.neutronCount = neutronCount;
}
}
如何定义氧气子类,使我可以输入可选参数(中子数)?如果我不输入参数,它将采用默认值class Oxygen extends Atom {
// By default, an oxygen atom has 8 neutrons but this can change.
// How can I define the subclass in such a way that Oxygen has
// 8 neutrons by default?
}
?
答案 0 :(得分:3)
class Oxygen extends Atom {
constructor(neutronCount = 8) {
// ---------------------^^^^
super(neutronCount);
}
}
大约等于:
class Oxygen extends Atom {
constructor(neutronCount) {
if (neutronCount === undefined) {
neutronCount = 8;
}
super(neutronCount);
}
}
因此8
将在new Oxygen()
和new Oxygen(undefined)
中使用。
如果愿意,您甚至可以在调用super
之前添加一些范围检查(如果有合理范围的话)。我对分子物理学(还是化学?)一无所知,但是例如,如果仅5 <= x <10的范围是合理的,则:
class Oxygen extends Atom {
constructor(neutronCount = 8) {
if (neutronCount < 5 || neutronCount >= 10) {
throw new Error(`Oxygen cannot have a neutron count of ${neutronCount}`);
}
super(neutronCount);
}
}
答案 1 :(得分:0)
另一个选择是混合类:
class Atom { }
const AtomWithDefault = defaultNeutrons => class AtomWithDefault extends Atom {
constructor(neutronCount = defaultNeutrons) {
this.neutronCount = neutronCount;
}
};
const Oxygen = AtomWithDefault(8);
console.log(new Oxygen(9), new Oxygen);