【问题标题】:Constructor Based Inheritance in JavaScriptJavaScript 中基于构造函数的继承
【发布时间】:2014-06-04 23:34:51
【问题描述】:

我有以下代码:

        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);

如果您查看构造函数中的第一条语句“Player”,您会看到我调用了函数 Box;我正在尝试将“Box”的属性和方法继承到“Player”中。我没有收到任何错误,但是当我尝试引用继承的属性(最后一条语句)时,它返回 undefined。

为什么 Player 不继承 Box 的属性?我知道 JS 是基于原型的,这是非常不正统的,但我无法理解如何使用原型通过多个对象进行继承。

【问题讨论】:

  • 使用Box.call(this, Size, Position)
  • 谢谢!一个问题:为什么函数不自动假设'this'的范围?
  • 更多关于继承、构造函数和原型的信息在这里。stackoverflow.com/questions/16063394/…

标签: javascript inheritance constructor this


【解决方案1】:

它不会以这种方式继承Box 的属性。这是因为您在全局上下文中调用Box 函数,而this 的值将指向全局对象window。要更改函数内this 的值,请使用call()apply() 甚至bind()。 当您在Player 函数中以这种方式更改this 的值时,Box 中的初始化代码将以Player 的实例作为其上下文运行。

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

【讨论】:

    【解决方案2】:

    另一个选项是设置 Player 的原型:

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

    那么你就不会直接调用 Box 构造函数了。它会为你调用,所以:

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

    【讨论】:

    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2012-06-26
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多