JS OOP初学者培训出错

时间:2014-12-09 08:29:27

标签: javascript oop

我是编程新手,我正在学习JavaScript OOP,尝试用坦克制作游戏。我有一些代码,但它没有正常工作,我需要一些帮助来了解它是如何工作的。请检查并告诉我如何解决问题,因为我想添加更多种类的坦克,但在此之前我需要修复代码。

var Tank = (function () {
    function Tank(name) {
        this._name = name;
    }

    Tank.prototype.getWeight = function () { return this._weight; }
    Tank.prototype.getName = function () { return this._name; }

    return Tank;
}());



var SmallTank = (function () {
    this.prototype = Object.create(Tank.prototype);

    function SmallTank(name) {
        Tank.apply(this._name);
    }

    SmallTank.prototype._weight = 2;

    return SmallTank;
}());

var myTank = new SmallTank("Aleks Tank");

console.log(myTank.getWeight());

2 个答案:

答案 0 :(得分:2)

似乎你只是想做某种继承;通常,您可以通过将父实例分配给子项的原型来完成此操作。

我想你会想要这样的东西:

var SmallTank = (function () {
  function SmallTank(name) {
      Tank.call(this, name);
      this._weight = 2;
  }
  SmallTank.prototype = new Tank();

  return SmallTank;
}());

或者,您可以指定Object.create(Tank.prototype)

答案 1 :(得分:1)

以下是按照Mozilla指南执行您尝试执行的操作的另一种方法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

var Tank = function (name) {
    this.name = name;
};
Tank.prototype.getName = function () { return this.name; };


var SmallTank = function (name) {
    Tank.call(this, name);
    this.weight = 2;
};
SmallTank.prototype = Object.create(Tank.prototype);
SmallTank.prototype.constructor = SmallTank;
SmallTank.prototype.getWeight = function () { return this.weight; };

var myTank = new SmallTank("Aleks Tank");
console.log(myTank.getName());
console.log(myTank.getWeight());