Skip to content

JavaScript mixin | Object

  • by

JavaScript Mixin is a way properties are added to objects without using inheritance. JavaScript doesn’t support multiple inheritances and if you need to add the functionality of 2 classes into a single object then use it.

Mixin – is a generic object-oriented programming term: a class that contains methods for other classes.

As functions are first-class objects, they can be added to an object precisely the same way. Object.assign is the way to add the properties of one object to another object.

You can add the property to the prototype:

Object.assign(Test.prototype, mixin);

You could add it in the constructor to every object created:

constructor() {
    this.var1 = 'var1';
    Object.assign(this, mixin);
}

You could add it in the constructor based on the condition:

constructor() {
    this.var1 = 'var1';
    if (someCondition) {
        Object.assign(this, mixin);
    }
}

Or you could assign it to an object after it is made:

let test = new Test();
Object.assign(test, mixin);

JavaScript mixin

Simple example code copying properties from one object to another. Person class object copying methods.

<!DOCTYPE html>
<html>
<body>

  <script>
    let sayHiMixin = {
     sayHi() {
      console.log(`Hello ${this.name}`);
    },
    sayBye() {
      console.log(`Bye ${this.name}`);
    }
  };

  class Person {
   constructor(name) {
    this.name = name;
  }
}
    // copy the methods
    Object.assign(Person.prototype, sayHiMixin);
    new Person("John").sayHi();

    var p = new Person('Mixin')
    p.sayHi()
    p.sayBye();
  </script>

</body>
</html>

Output:

JavaScript mixin

Mixins are often used in JavaScript frameworks and libraries to add reusable functionality to objects or classes. They provide a flexible way to compose objects with different sets of behaviors. However, it’s important to be cautious when using mixins, as they can lead to complex code and potential conflicts if not managed carefully.

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading