无法在ES6类定义中定义原型属性 [英] Cannot define prototype properties within ES6 class definition
问题描述
我正在尝试ES6语法并发现我无法在类定义中定义原型属性或实例属性,为什么禁止它?
我使用的是 MyClass.prototype.prop = 1
之前,按照下面的babel编译器尝试ES7,仍然无法定义原型属性。
class MyClass {
prop = 1;
static sProp = 1;
}
我不认为定义实例属性是危险的,有2个案例在我自己的浏览器游戏需要原型属性:
-
子类实例需要从基类继承相同的属性值:
var Building = function(){...}
Building.prototype.sight = 350;
TerranBuilding.CommandCenter = ...(CommandCenter扩展建筑物)
TerranBuilding.Barracks = ...(军营延伸建筑物)
因此,CommandCenter和军营将拥有与350相同的建筑物视野。
新的CommandCenter()。视线===新军营()。视线//所有建筑物都有相同的视线
-
缓冲区效果覆盖原始属性并删除缓冲区
Marine.prototype.speed = 20
var unit = new Marine()
unit.speed === 20 //获取单位。 __proto __。速度20
unit.speed = 5 //缓冲区:减慢速度,unit.speed将覆盖单位.__ proto __。速度
删除unit.speed //删除缓冲区
unit.speed === 20 //真实,速度恢复
所以我认为它应该添加一种方法来设置原型属性而不是完全禁止它,或者你能提供一些其他解决方案来处理上述2种情况吗?
这些都不会出现在类原型上。
类Foo {bar = 1; }
语法将为类实例,使用 this.bar
进行访问。
类Foo {静态条= 1; }
语法将为 Foo.bar 进行访在这种情况下,没有太多理由使用原型。它只会使实际拥有该属性的人变得复杂,并且在几个不同的类中分配一个数字将具有非常小的开销。
我建议使用类实例属性,只需在需要的地方使用 this.sight
。
I was trying ES6 syntax and find I cannot define prototype property or instance property within class defination, why forbids it?
I was using MyClass.prototype.prop=1
before, try ES7 by babel compiler as below, still cannot define prototype property.
class MyClass{
prop=1;
static sProp=1;
}
I don't think define instance property is any dangerous, there's 2 cases in my own browser game need prototype property:
Subclass instances need to inherit same property value from base class:
var Building=function(){...} Building.prototype.sight=350; TerranBuilding.CommandCenter=...(CommandCenter extends Building) TerranBuilding.Barracks=...(Barracks extends Building)
So CommandCenter and Barracks will both have same building sight as 350.
new CommandCenter().sight===new Barracks().sight//All buildings have same sight
Buffer effect override original property and remove buffer
Marine.prototype.speed=20 var unit=new Marine() unit.speed===20//get unit.__proto__.speed 20 unit.speed=5//Buffer:slow down speed, unit.speed will override unit.__proto__.speed delete unit.speed//Remove buffer unit.speed===20//true, speed restore
So I think it should add a way to set prototype property instead of forbid it completely, or can you give some other solutions to deal with above 2 cases?
Neither of those will be on the class prototype.
The class Foo { bar = 1; }
syntax will assign a value to the class instance, to be accessed with this.bar
.
The class Foo { static bar = 1; }
syntax will assign a value to the class constructor, to be accessed with Foo.bar
.
There isn't much reason to use the prototype in this case. It will only complicate who actually owns the property and assigning a number in a few different classes will have very little overhead.
I would suggest the class instance property and just use this.sight
everywhere you need it.
这篇关于无法在ES6类定义中定义原型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!