【发布时间】: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