别名或以其他方式合并具有不同名称

时间:2016-05-13 18:12:34

标签: javascript json oop object inheritance

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

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

两者都完全一样,看起来很尴尬。是否可以将它们合并到一个名为' Entity'的对象中,并通过不同的名称(原始' Tag'和'类别')引用它们?

由于我需要在原型中引用当前的原型名称,这可能会更加复杂。

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

我如何应用相同的' toJSON'扩展到'实体'对象,但要确保它返回'标记'或者'类别'在' __类型'字段,取决于使用哪个对象?

1 个答案:

答案 0 :(得分:2)

我会做这样的事情:



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());
&#13;
&#13;
&#13;

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

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');
  }
});