未加星标

Understanding Mixins in JavaScript

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

In this article, we will look deep into the heart of mixins to learn what they are and to know when to apply them.

What areMixins?

Here are different definitions of mixin by great developers

Mixin is a way properties are added to objects without using inheritance― DarrenJones

Mixins provide an alternate way of composing your application that isn’t explicitly covered in books on design patterns.― SteveFenton

Mixins are a form of object composition, where component features get mixed into a composite object so that properties of each mixin become properties of the composite object.― EricElliot

We see now that mixins mix different object’s properties into one object, so the object has all the objects’ properties and methods.

Tip: Software composition is a great way to build scalable and maintainable applications. Use open-source tools like Bit to easily share, compose and build with smaller components and functionalities to speed and scale this process.

Bit―Share and build with code components

Bit helps you share, discover and use code components between projects and applications to build new features and… bitsrc.io

Let’s see a simple example of mixins:

// mixin_ex.js const mydetails = {} const firstname = { firstname: "Nnamdi" } const surname = { surname: "Chidume" } const occupation = { occupation: "Software Developer" } const nationality = { nationality: "Nigerian" } log(mydetails) Object.assign(mydetails,surname, firstname, occupation, nationality); log(mydetails)

this logs:

$ node mixin_ex { } { firstname: "Nnamdi", surname: "Chidume", occupation: "Software Developer", nationality: "Nigerian" }

Did you notice anything? Remember, we started mydetails object as an empty object. But after several magical stuff, the mydetails object was no longer empty in the end. It came to have all the properties of all other objects below it.

Yes, this is what mixin is all about. To combine the properties of different objects into a single object.

It wasn’t magical we used the good old Object.assign method to compose the objects into the mydetails object.

Object.assign is used to copy the values of properties from one or more objects to the desired object.

We see now that, Object.assign provides the basis in javascript for mixin properties between objects(objects without classes).

Object.assign(target, ...sources);

It takes as first argument the target object and then accepts all the objects to mixed with the target object as a rest ... argument.

So, now we know what Object.assign is and what it does. Let’s relate it back to our example.

From our example, mydetails was passed in as the target and surname, firstname, occupation, nationality objects were passed as the sources, i.e the objects from properties are to be copied from.

It then composes/copies the properties from the objects to mydetails. So when we run log(mydetails) , we see the properties all defined in the mydetails object.

Object.assign composes only dynamic objects Object.assign copies the properties. Implementing our own Object.assign

Let’s implement our own version of Object.assign to learn how the composition of properties in objects works.

First, we monkey-patch the assign method in the Object class:

Object.prototype.assign = function assign(dest, ...src) { }

We check if the dest argument is an object:

Object.prototype.assign = function assign(dest, ...src) { if(typeof dest == 'object') { } }

We loop through the src array and check if the current object in the array is an object. If so, we loop through its properties using the for..of loop and copy each property to dest with reference to the property name using the = operator:

Object.prototype.assign = function assign(dest, ...src) { if(typeof dest == 'object') { for(let s of src) { if(typeof s == 'object'){ for(prp of Object.keys(s)){ dest[prp] = s[prp] } } } } }

So we have our own Object.assign method. We can now test the monkey-patch:

Object.prototype.assign = function assign(dest, ...src) { if(typeof dest == 'object') { for(let s of src) { if(typeof s == 'object') { for(prp of Object.keys(s)) { dest[prp] = s[prp] } } } } } const mydetails = {} const firstname = { firstname: "Nnamdi" } const surname = { surname: "Chidume" } const occupation = { occupation: "Software Developer" } const nationality = { nationality: "Nigerian" } Object.assign(mydetails, surname, firstname, occupation ,nationality); log(mydetails)

It will log the same result as our previous example. You have seen how to copy properties from one object to another. The above implementation was possible because JavaScript supports dynamic objects ( objects without classes).

Mixing Classes

Mixins can also be applied to classes in JavaScript.

We can create a class by doing this:

class Car {}

This is an empty class, without properties and methods. To make the Car functional, we have to give it properties and methods in other it could be driven.

class Wheel { drive() { //... } } class Tyre { brake() { //... } } class Steering{ steer(x, y) { //... } } class Wiper { wipe(speed) { //... } } class Engine { start() { //... } }

Wheel drives, Tyre brakes, Steering -wheel steers, Wiper wipes and Engine starts. You know, it's more like a poem.

We can mix all these classes into the Car class, so we could drive it.

Using our good o’l Object.assign won't work in this case.

//assign_ex.js //... Object.assign(Car, Engine, ...) new Car().start() $ node assign_ex.js C:\wamp\www\developerse\projects\trash\assign.js:56 new Car().start() ^ TypeError: (intermediate value).start is not a function at Object.<anonymous> (C:\wamp\www\developerse\projects\trash\assign_ex.js:56:5) at Module._compile (internal/modules/cjs/loader.js:678:30) ...

OR

//assign_ex.js //... let engine = Engine(); car = Object.assign(car, engine, ...); car.start() $ node assign_ex.js C:\wamp\www\developerse\projects\trash\assign.js:56 car.start() ^ TypeError: car.start is not a function at Obj

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Understanding Mixins in JavaScript
本站链接:https://www.codesec.net/view/621368.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(44)