【问题标题】:Aliasing or otherwise merging two identical object prototypes with different names别名或以其他方式合并具有不同名称的两个相同对象原型
【发布时间】:2016-09-10 01:08:30
【问题描述】:

我有两个这样的对象原型:

function Tag(name, description) {
    this.name = name;
    this.description = description || null;
}
function Category(name, description) {
    this.name = name;
    this.description = description || null;
}

两者一模一样,看起来很别扭。是否可以将它们合并到一个名为“Entity”的对象中,并用不同的名称(原始的“Tag”和“Category”)引用它们?

这可能会因为我需要在原型中引用当前原型名称而变得更加复杂。

Tag.prototype.toJSON = function() {
    return {
        __type: 'Tag',
        name: this.name,
        description: this.description
    };
};

如何将相同的“toJSON”扩展应用到“Entity”对象,但确保它在“__type”字段中返回“Tag”或“Category”,具体取决于所使用的对象?

【问题讨论】:

  • 我不会打扰。您的代码更清晰。
  • 公平的答案!那我就坚持下去。我总是很想知道是否有更好的方法!

标签: javascript json oop object inheritance


【解决方案1】:

我会这样做:

Dummy = function () {};

Entity = function (name) {
  this.name = name;
};

Entity.prototype.toString = function () {
  return "My name is " + this.name + ".";
};

A = function () {
  Entity.call(this, 'A');
};

Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = A;
A.prototype = new Dummy();

B = function () {
  Entity.call(this, 'B');
};

Dummy.prototype = Entity.prototype;
Dummy.prototype.constructor = B;
B.prototype = new Dummy();

document.body.innerHTML = ""
+ (new A()) + "<br />"
+ (new B());

这是一个让事情变得更清洁的小功能(希望如此):

function Nothing () {};

function extend (Sup, proto) {
  function Class () {
    if (this.init) {
      this.init.apply(this, arguments);
    }
  }
  Nothing.prototype = Sup.prototype;
  Nothing.prototype.constructor = Sup;
  Class.prototype = new Nothing();
  delete Nothing.prototype;
  for (var k in proto) {
    Class.prototype[k] = proto[k];
  }
  return Class;
}

这里是如何使用它:

Entity = extend(Nothing, {
  init: function (name) {
    this.name = name;
  },
  toString: function () {
    return "My name is " + this.name + ".";
  }
});

A = extend(Entity, {
  init: function () {
    var sup = Entity.prototype;
    sup.init.call(this, 'A');
  }
});

B = extend(Entity, {
  init: function () {
    var sup = Entity.prototype;
    sup.init.call(this, 'B');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多