JS OOP 初学者培训的错误

Error for JS OOP beginner training

本文关键字:错误 培训 初学者 OOP JS      更新时间:2023-09-26

我是编程新手,我正在学习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());

似乎您只是在尝试进行某种继承; 通常,通过将父实例分配给子实例的原型来执行此操作。

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

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

或者,您可以分配Object.create(Tank.prototype) .

这是另一种方法,按照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());