[英]using functions inside javascript constructors
我需要為對象編寫一個構造函數,該構造函數為該對象的color屬性提供一個隨機值。 這就是我寫的
var Ghost = function() {
// your code goes here
var num = Math.floor(Math.rand()*4);
if(num === 0){
this.color = "white";
}
else if(num === 1){
this.color = "yellow";
}
else if(num === 2){
this.color = "purple";
}
else if(num === 3){
this.color = "red";
}
};
我從代碼戰的測試套件中收到一條錯誤消息
TypeError: Object #<Object> has no method 'rand'
at new Ghost
at Test.describe
我是否不允許在構造函數中使用函數,或者我不理解的測試套件有什么問題?
該函數的名稱是Math.random
,而不是Math.rand
。
解釋錯誤消息:
TypeError: Object #<Object> has no method 'rand'
首先嘗試使用您要調用的“ rand”方法查找對象。 在這種情況下,它是數學。 然后,驗證所討論的對象確實具有該方法。
無關緊要的是,您的選擇代碼可以簡化為:
var COLOURS = ['white', 'yellow', 'purple', 'red'];
this.color = COLOURS[Math.floor(Math.random() * 4)];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.