Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
JavaScript mixin as a class

I found this technique to create a mixin:

let fooMixin = {
    foo() {console.log('foo')},
};

class A {
    bar() {console.log('bar')}
}

Object.assign(A.prototype, fooMixin);

however I would prefer to use class syntax also for the mixin.

I tried this:

class FooMixinClass {
    foo() {console.log('foo')}
}

class B {
    bar() {console.log('bar')}
}

Object.assign(B.prototype, FooMixinClass.prototype);

let b = new B();
b.bar();
b.foo();

but get this error:

"bar"

TypeError: b.foo is not a function. (In 'b.foo()', 'b.foo' is undefined)"

I would like to understand why it doesn't work, since inspecting FooMixinClass.prototype at runtime reveals an object almost identical to fooMixin.

Fiddle: https://jsfiddle.net/a5ufjchz/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I would like to understand why it doesn't work, since inspecting FooMixinClass.prototype at runtime reveals an object almost identical to fooMixin.

The keyword is almost. Methods on a class are not enumerable and Object.assign() only copies properties that are enumerable and not inherited

A utility-function:

class FooMixinClass {
  static foo() {
    console.log("foo, but static");
  }
  foo() {
    console.log('foo')
  }
}

class B {
  bar() {
    console.log('bar')
  }
}

function mixin(target, source) {
  // ignore the Function-properties
  const {name,length,prototype,...statics} = Object.getOwnPropertyDescriptors(source);
  Object.defineProperties(target, statics);
  // console.log("static", statics);

  // ignore the constructor
  const {constructor,...proto} = Object.getOwnPropertyDescriptors(source.prototype);
  Object.defineProperties(target.prototype, proto);
  // console.log("proto", proto);

  return target;
}

mixin(B, FooMixinClass);

let b = new B();
b.bar();
b.foo();
B.foo();
.as-console-wrapper{top:0;max-height:100%!important}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!