guilin 桂林
guilin 桂林

Reputation: 17422

how to mixup 2 class in javascript?

Here are two JavaScript classes written by others, I need to use both of them:

  1. filter.js
  2. validator.js

I need to mix them up into a single class - it could be Validator or Filter class, or some class I define but I have to do this after Validator Filter initialized.

Upvotes: 0

Views: 87

Answers (2)

user1046334
user1046334

Reputation:

function mixin(dst, src) {
  for (var p in src) {
    if (src.hasOwnProperty(p)) { dst[p] = src[p]; }
  }
  return dst;
}

var mixedProto = mixin(mixin({}, Filter.prototype), Validator.prototype);

var f = new Filter(), v = new Validator();

var siameseTwins = mixin(mixin(Object.create(mixedProto), f), v);

In case you do not have Objct.create or are afraid of using ES5 (no point, everything already have it except old things), you can define Object.create as

function (proto) {
  function f () {}
  f.prototype = proto;
  return new f;
}

Upvotes: 1

Esailija
Esailija

Reputation: 140236

Since validator constructor is empty already you could do:

Filter.prototype = new Validator();
Filter.prototype.constructor = Filter;

Filter.prototype.modify = ...

...

... means adding all the filter methods to filter prototype like you are doing in the filter file.

But I need do this after Filter and Validator initialized

You could try something like this then:

    var a = new Validator(),
        b = new Filter(); //They are initialized

    var tmp = Filter.prototype,
        key;

    Filter.prototype = a;

    for( key in tmp ) {
    Filter.prototype[key] = tmp[key];
    }

    Filter.prototype.constructor = Filter;

b ( a Filter instance ) will now have all Filter and Validator methods

Upvotes: 2

Related Questions