2016-06-24 104 views
-2

我试图从我的构造函数访问属性,但我一直在获取“未捕获TypeError:无法读取未定义的属性'长度'。我试图访问的属性是数组this.possibleX。请指教。谢谢!错误:未捕获TypeError:无法读取未定义的属性'长度'

var Item = function() { 
    this.x = this.positionX(); 
    this.y = this.positionY(); 
    this.sprite = this.spritePic() 
    this.possibleX = [0,100,200,300,400]; 
    this.possibleY = [80,160,240,320]; 
    this.spriteOptions = ['images/Rock.png','images/Rock.png','images/Rock.png','images/Heart.png','images/Gem Blue.png', 'images/Gem Green.png', 'images/Gem Orange.png']; 
} 

Item.prototype.positionX = function() { 
    var startX = this.possibleX[Math.round(Math.random() * this.possibleX.length)]; 
    return startX; 
} 

var item = new Item(); 
+0

到目前为止您尝试了什么?错误消息非常简单:this.possibleX未定义。 – Sebastianb

+0

你有做过任何研究吗?看看这个评论的右边,在那个区域里有一个有10个问题的相关部分,所有部分都有相同的错误信息。 –

+0

我是javascript的新手。我认为这是一个访问问题,因为“这个”变量使用不当,所以我正在了解有关调用,绑定和申请工作的方式,但似乎并不是正确的方法。感谢您的有用评论!新的在这里,并已经热爱社区! :) – Richard

回答

1
var Item = function() { 
    this.x = this.positionX(); 

注意你是如何第一次调用该函数,然后定义this.possibleX = [0,100,200,300,400];。您需要反转此顺序。

+0

非常感谢你!这帮助我节省了很多时间!干杯 – Richard

相关问题