Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript原型继承-2个对象使用自己的原型方法,但只调用1个_Javascript_Inheritance_Prototype - Fatal编程技术网

javascript原型继承-2个对象使用自己的原型方法,但只调用1个

javascript原型继承-2个对象使用自己的原型方法,但只调用1个,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,编辑 我仍然想知道为什么会发生这种情况,但在阅读了一些关于原型的资料后,我的解决方案是不让这两个对象覆盖基本原型,因为根据这一点 我有三个物体 基本对象称为对象控件 对象moneyBag和对象movementPad都继承控件的原型 money bag和movementPad都有两个不同的绘图函数,因此代码如下所示 Money.prototype.Draw = function (context) { console.log("foo2"); } MovementPad.prototyp

编辑 我仍然想知道为什么会发生这种情况,但在阅读了一些关于原型的资料后,我的解决方案是不让这两个对象覆盖基本原型,因为根据这一点

我有三个物体

基本对象称为对象控件

对象moneyBag和对象movementPad都继承控件的原型

money bag和movementPad都有两个不同的绘图函数,因此代码如下所示

Money.prototype.Draw = function (context) {
    console.log("foo2");
}

MovementPad.prototype.Draw = function (context) {
    console.log("foo1");
}
在我的HUD.js中,这两个对象都是初始化的,然后HUD调用这两个对象

var movementControl = new MovementPad(screenManager, 1,1,1,1);

var money = new Money(screenManager, 10, 10, 37, 36);

   // .... code skipped
this.Draw = function (context) {
    movementControl.Draw(context);
    money.Draw(context);
}
我的问题是这两个对象都没有调用它们的draw方法。如果我首先初始化movementPad,那么将调用draw方法,如果我首先初始化money,那么只调用draw方法

由于原型的两种绘制方法都没有被调用,我错过了对原型的理解/做错了什么

(更多代码如下)

movementPad.js

MovementPad.prototype = control.prototype;
MovementPad.prototype.constructor = MovementPad;

function MovementPad(screenManager, x, y, width, height) {
    "use strict"
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

    //.... code skipped

    MovementPad.prototype.Draw = function (context) {
        context.drawImage(movementPad, x, y , width ,height);

    }
}

Money.js

Money.prototype = control.prototype;
Money.prototype.constructor = Money;

function Money(screenManager, x, y, width, height) {
    "use strict"
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

  //.... code skipped

    Money.prototype.Draw = function (context) {
        context.drawImage(moneyBag, x, y, width, height);
    }
}

您已将相同的
control.prototype
实例分配给
Money
MovementPad
的原型,因此您的
Draw
方法声明相互碰撞

将原型设置为单独的实例:

Money.prototype = new control();
// ...
MovementPad.prototype = new control();

而且你的
绘图
作业应该有效

你将它设置为移动键盘。原型和货币。原型都指向同一个对象,
control.prototype
,所以当你向第二个定义的函数添加一个
Draw
函数时,它会覆盖第一个定义的函数的
Draw
函数。谢谢,这就是我想要的答案,我已经有一段时间没有使用堆栈溢出了,所以我想知道你在回答问题时的评论标记是什么,我似乎找不到它>.user1502147-没关系,接受@hurrymapelad的回答就行了。你不能“接受”评论。
Money.prototype = new control();
// ...
MovementPad.prototype = new control();