devSoyoung / STUDY

✏️ 공부한 내용 정리, 주제에 따라 분류
4 stars 1 forks source link

[ES6] 믹스인(Mixin) 패턴, Object.assign() #28

Open devSoyoung opened 4 years ago

devSoyoung commented 4 years ago

상속 관련 참고 글 : JavaScript Inheritance: Pseudoclassical vs. Prototypal

Mixin 구현

function mixin(receiver, supplier) {
  Object.keys(supplier).forEach(function(key) {
    receiver[key] = supplier[key];
  });

  return receiver;
}

Mixin 패턴의 활용

Reference

devSoyoung commented 4 years ago

[ES6] Object.assign()

underscore의 Mixin 구현

  // Helper function to continue chaining intermediate results.
  var chainResult = function(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    _.each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return chainResult(this, func.apply(_, args));
      };
    });
    return _;
  };