Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - Cannot define prototype properties within ES6 class definition

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:

  1. 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
  1. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...