2011-12-25 44 views
3

我在聖誕節那天試圖使它變成「雪」時有點麻煩。我想出瞭如何抓住一天,但我不知道如何正確地調用SnowStorm()。在聖誕節當天致電一個功能

var christmas = { 
    month: 11, 
    date: 25 
} 

function isItChristmas() { 
    var now = new Date(); 
    var isChristmas = (now.getMonth() == christmas.month && now.getDate() == christmas.date); 

if (isChristmas) 
    return ; 
    else 
    return ; 
} 

var snowStorm = null; 

function SnowStorm() { 
    (snowstorm code) 

} 

snowStorm = new SnowStorm(); 
+1

哪一點是你卡在具體? 'isItChristmas'部分?如何將'snowStorm()'函數放入空的'if()'語句中?還有別的嗎? – Bojangles 2011-12-25 22:35:26

回答

1

這裏的,如果你打算做一個函數的版本(不是類):

var christmas = { 
    month: 11, 
    date: 25 
} 

function isItChristmas() { 
    var now = new Date(); 
    return (now.getMonth() == christmas.month && now.getDate() == christmas.date); 
} 

if (isItChristmas()){ 
    SnowStorm(); 
    }else{ 
    //not a christmas 
} 

function SnowStorm() { 
    (snowstorm code) 
} 

這裏的,如果你打算做一個等級:

var christmas = { 
    month: 11, 
    date: 25 
} 

function isItChristmas() { 
    var now = new Date(); 
    return (now.getMonth() == christmas.month && now.getDate() == christmas.date); 
} 

var storm = new SnowStorm(); 

if (isItChristmas()){ 
    storm.Snow(); 
    }else{ 
    //not a christmas 
} 

function SnowStorm() { 
    this.Snow = function(){ 
     (snowstorm code) 
    } 
} 
0

您需要從isItChristmas函數返回一個布爾值:

function isItChristmas() { 
    var now = new Date(); 
    return (now.getMonth() + 1 == christmas.month && 
      now.getDate() == christmas.date); 
} 

然後調用它:

function SnowStorm() { 
    if (isItChristmas()) { 
     // your snowstorm code here 
     // that will execute only on Christmas 
    } 
} 

順便問一下,你會發現,.getMonth()方法返回從0到11個月,所以你需要添加1,如我的例子所示,否則你的代碼將在11月25日運行。

0

首先,你沒有在isItChristmas函數上返回任何東西。 其次,在暴風雪功能只需添加

if (isItChristmas) { 
    (your code here) 
}