Javascript 如何使用父构造函数?
请帮忙解决这个问题。我有基类“单位”:Javascript 如何使用父构造函数?,javascript,oop,Javascript,Oop,请帮忙解决这个问题。我有基类“单位”: var Unit = function() { this.x_coord = x_coord; this.y_coord = y_coord; this.color = color; }; 儿童班“playerUnit”: var playerUnit = function(gameObj, x_coord, y_coord, color) { Unit.apply(this, arguments); }; playerUnit.p
var Unit = function() {
this.x_coord = x_coord;
this.y_coord = y_coord;
this.color = color;
};
儿童班“playerUnit”:
var playerUnit = function(gameObj, x_coord, y_coord, color) {
Unit.apply(this, arguments);
};
playerUnit.prototype = Object.create(Unit.prototype);
var Game = function(options) {
new playerUnit(this,1,1,'red');
};
var app = new Game();
我计划在将来做很多这样的子类:“enemyUnit”、“tankUnit”、“boatUnit”等等,我需要使用公共属性:x_coord、y_coord、color
i try use Unit.apply(this, arguments);
但在启动脚本后,我在控制台中看到以下错误消息:
未捕获引用错误:未定义x_坐标
jsIDLE:您应该在
单元中定义参数
:
var Unit = function(gameObj, x_coord, y_coord, color) {
// ...
};
还考虑传递对象以避免在所有函数中重复这些参数。
var Unit = function(data) {
this.x_coord = data.x_coord;
this.y_coord = data.y_coord;
this.color = data.color;
};
var playerUnit = function(data) {
Unit.call(this, data);
};
new playerUnit({
gameObj: this,
x_coord: 1,
y_coord: 1,
color: 'red'
});
您的父构造函数没有定义任何参数。如果你只做了
newunit(…)
,它也不起作用,这与你的子类无关(这很好)。Unit
不使用gameObj
。但这是一个近乎打字错误的问题。