質問

I have the following code:

        function Vector(X,Y) //Constructor
        {
            this.X = X;
            this.Y = Y;
        }

        function Box(Size /*Vector*/, Position /*Vector*/) //Constructor
        {
            this.Size = Size;
            this.Position = Position;
            this.Velocity = new Vector(0,0);
            this.Anchored = true;
            this.CanCollide = false;
            this.Colour = "rgb(50,50,50)";

            this.draw = function()
            {
                ctx.fillStyle = this.Colour;
                ctx.fillRect(this.Position.X-(this.Size.X*0.5),this.Position.Y-(this.Size.Y*0.5),this.Size.X,this.Size.Y);
            }
        }

        function Player(Size,Position)
        {
            Box(Size,Position);
            this.Anchored = false;
            this.CanCollide = true;
            this.Colour = "rgb(0,100,0)";
        }

        var Me = new Player(new Vector(25,25), new Vector(10,10));
        console.log(Me.Velocity);

If you look at the first statement in the constructor function, 'Player', you'll see that I called the function Box; I'm trying to inherit the properties and methods of 'Box' into 'Player'. I don't get any errors, however when I try and reference an inherited property, (the last statement), it returns undefined.

Why doesn't Player inherit Box's properties? I understand that JS is prototype based, and that this is extremely unorthodox, but I cannot make any sense as to how to inherit through multiple objects using prototypes.

役に立ちましたか?

解決

It will not inherit the properties of Box that way. That is because you are calling the Box function on the global context and the value of this will point to the global object window. To change the value of the this inside the function, use call() or apply() or even bind(). When you change the value of this this way inside the Player function, the initialisation code inside Box will be run with the instance of Player as its context.

function Player(Size,Position)
 {
   Box.call(this,Size,Position); //the this value will point to instance of Player
}

他のヒント

Another options is to set Player's prototype:

Player.prototype = new Box();
Player.prototype.constructor = Player;

Then you wouldn't call the Box constructor directly. It would be called for you, so:

function Player(Size,Position)
{
    this.Size = Size;
    this.Position = Position;
    this.Anchored = false;
    this.CanCollide = true;
    this.Colour = "rgb(0,100,0)";
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top