Javascript classes: state management

栏目: IT技术 · 发布时间: 4年前

内容简介:In case you are working with the ES6+ class system, you most likely want to use configs (properties) for your own classes. Since the class system is still lacking to define these inline, you could use the constructor:You will most likely notice right away,

In case you are working with the ES6+ class system, you most likely want to use configs (properties) for your own classes. Since the class system is still lacking to define these inline, you could use the constructor:

Javascript classes: state management

You will most likely notice right away, that this approach is not really helpful, since you have no change listeners for your class configs. Defining the properties via get & set can help with this:

Javascript classes: state management

Both class definitions are pretty similar, but the 2nd one allows us to use myInstance.a = 2; for automatically triggering the setter. As a design pattern, saving the content of each property inside a underscore prefixed version does make sense (e.g. a => _a). You could add more logic into each setter, but as soon as you want to extend your own classes again, this will cause problems. So calling new methods which you can extend or override makes more sense:

Javascript classes: state management

Passing the new & the old value makes a lot of sense. As a design pattern, I recommend to use method names like afterSetMyConfig(). In case you want to extend your class now, you can override afterSetA and use the superclass call (super.afterSetA(value, oldValue);) as needed.

In case you are using the neo.mjs framework , you can shorten this code quite a bit:

Javascript classes: state management

applyClassConfig will generate something similar to the previous version, with the difference that you can change the default values for your properties more easily when extending classes.

Chicken or egg?

You might have noticed that afterSetA() is using this.b internally. You could flip the order of a_ & b_ inside the getConfig() method to change the order in which the configs do get applied. Since afterSetB() is using this.a internally, we ended up with a circular reference , so we can not solve this issue just using the config order. In neo.mjs, i solved it like this:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java解惑

Java解惑

布洛赫、加夫特 / 陈昊鹏 / 人民邮电出版社 / 2006-1 / 39.00元

本书特写了95个有关Java或其类库的陷阱和缺陷的谜题,其中大多数谜题都采用了短程序的方式,这些程序的行为与其看似的大相径庭。在每个谜题之后都给出了详细的解惑方案,这些解惑方案超越了对程序行为的简单解释,向读者展示了如何一劳永逸地避免底层的陷阱与缺陷。 本书趣味十足、寓教于乐,适合于具备Java知识的学习者和有编程经验的Java程序员。一起来看看 《Java解惑》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具