创建新的子类对象时设置父类中定义的变量时出现问题

Trouble setting variables defined in parent class when creating a new subclass object

本文关键字:变量 定义 问题 设置 子类 对象 创建 父类      更新时间:2023-09-26

我一直在尝试学习Javascript继承结构的来龙去脉,但我遇到了这个问题。我正在尝试创建多个子类对象,并通过在创建时传递变量来立即为它们赋值。

例如,在父类下面,GamePiece在创建时接收一个随机属性作为变量,并将其设置为myProperty这在创建新的GamePiece对象时当然可以正常工作。但是,如果我想在创建 Pawn 对象时设置该变量,它不会传递到其父对象并且保持未设置状态。显而易见的解决方法是只在子类上再次定义变量,但是,如果我错了,请纠正我,这似乎违背了定义父类的目的。您也可以通过将参数作为Pawn.prototype = new GameObject("foo");传递来成功设置变量,但这在创建多个Pawn()对象时没有帮助。有没有我缺少的常用方法?

var GamePiece = function (randomProperty) {
  this.myProperty = randomProperty || "never set";
  this.print = function () {
    console.log(this.myProperty);
  }
}
var Pawn = function (randomProperty) {
  this.print = function () {
    console.log(this.myProperty);
  }
}
//Setting a value on creation
piece = new GamePiece("foo");
piece.print(); // Produces "foo" naturally
//Setting the prototype
Pawn.prototype = new GamePiece();
//Try to pass value through the creation of subclass
pawn = new Pawn("foo");
pawn.print(); // Produces "never set"

您必须在当前this的上下文中调用父类,使用callapply方法:

var GamePiece = function (randomProperty) {
    this.myProperty = randomProperty || "never set";
    this.print = function () {
        console.log(this.myProperty);
    }
}
var Pawn = function (randomProperty) {
    Game.call(this, randomProperty);
    // or Game.apply(this, [randomProperty]);
}

但是最好将方法保留在原型中。所以下一个代码会更好:

var GamePiece = function (randomProperty) {
    this.myProperty = randomProperty || "never set";
    //... some another properties initialization
};
GamePiece.prototype.print = function () {
    console.log(this.myProperty);
};
var Pawn = function (randomProperty) {
    Game.call(this, randomProperty);
    // or Game.apply(this, [randomProperty]);
    //... some Pawn properties initialization
};
Pawn.prototype = Object.create(Game.prototype, { constructor: { value: Pawn }});
Pawn.prototype.someMethod = function() {
    // Some Pawn method logic
};

但是 ES6 即将到来(将于 2015 年 6 月recommendation),因此您可以开始准备使用它们。看这里,这里和这里