[JS Pattern] Mixin Pattern
JS pattern Mixin
2023-09-14 09:00:45 时间
Add functionality to objects or classes without inheritance
Although we can add functionality iwht mixins without inheritance, mixins themselves can use inheritance
class Dog { constructor(name) { this.name = name; } } const animalFunctionality = { walk: () => console.log("Walking"), sleep: () => console.log("Sleeping") }; const dogFunctionality = { __proto__: animalFunctionality, bark: () => console.log("Woof!"), wagTail: () => console.log("Wagging my tail"), play: () => console.log("Plyaing!"), walk(){ super.walk() }, sleep(){ super.sleep() } }; // Object.assign(dogFunctionality, animalFunctionality); Object.assign(Dog.prototype, dogFunctionality); const pet1 = new Dog("Daisy"); console.log(pet1.name); pet1.bark(); pet1.play(); pet1.walk(); pet1.sleep();
Suggestion:
Mixins were often used to add functionality to React component before the introduction of ES6 classes. The React team discourages the use of mixins as it easily adds uncessary complexity to a component, making it hard to maintain and reuse. The React eam encouraged the use of higher order components instead, which can now often be replaced by Hooks.
[Note] From JS Patterns Book
相关文章
- webview和js交互
- js中数组的splice()方法
- js navigator.wakeLock 保持屏幕唤醒状态
- vue.js3: 用crypto-js做sha加密(vue@3.2.37 / crypto-js@4.1.1)
- JS编辑器获取选择内容的HTML多浏览器兼容性写法(支持Chorme、Firefox)
- [Typescript] Convert a js project to typescript
- [JS Pattern] Container / Presentational Pattern
- js对象的引用传递在react中的使用注意事项
- 如何用js给老婆每天发情话?
- Atitit 项目界面h5化静态html化计划---vue.js 把ajax获取到的数据 绑定到表格控件 v2 r33.docx
- Atitit js版本es5 es6新特性
- 华为OD机试 - 单词倒序(Java & JS & Python)
- 华为OD机试 - 星际篮球争霸赛(Java & JS & Python)
- js延迟加载(异步操作)
- js 判断通过什么打开(安卓、苹果、微信、QQ、浏览器、某个app应用…)
- js 常用正则表达式
- js中内建对象
- JS字符串(string)