[英]Class syntax equivalent of adding a shared value to a prototype?
說我有這堂課
class banana {
constructor(weight) {
this.weight = weight;
}
}
banana.prototype.type = "fruit";
因此,不同的香蕉具有不同的權重,但是所有的香蕉都是水果,因此我想在原型中添加“ type = fruit”而不是實例。
但是,我不想在類聲明結束之后執行此操作,對於我來說,將方法和原型變量按其用途保持緊密聯系以提高可讀性對於我來說比較整潔。
在類括號內是否有語法可以做到這一點? 有點像
class banana {
type = "fruit" <- doesn't work of course
constructor(weight) {
this.weight = weight;
}
}
在類語句中,只允許使用方法,而沒有賦值。 因此,如果要設置類型,則必須在構造函數中進行設置,如下所示:
class banana {
constructor(weight) {
this.weight = weight;
this.type = "fruit";
}
}
如果您不想這樣做,那么也可以將常量定義為一個函數,但這對我來說有點不客氣:
class banana {
constructor(weight) {
this.weight = weight;
}
static type() {return "fruit";}
}
您可以在構造函數中進行設置:
class Banana {
constructor() {
this.type = 'fruit';
}
}
或者您可以擁有一個Fruit類,其中Banana是其子類:
class Fruit {
constructor() {
this.type = 'fruit';
}
}
class Banana extends Fruit {
constructor() {
super();
}
}
或者,如果您使用的是Babel,則可以添加transform-class-properties插件 :
class Banana {
type = 'fruit';
}
// .babelrc
{
"plugins": [[
"transform-class-properties"
]]
}
您可以定義一個小的輔助函數:
const Type = prototype => Object.assign(function(){}, {prototype});
然后擴展它:
class Test extends Type({some:"prop"}) {
constructor(){
super();
//...
}
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.