2013-04-14 52 views
2

jQuery Datepicker構件基於內置的Date。我試圖重寫日期來計算我們自己的具有不同年份,月份的日曆....(無需更改日期選擇器代碼)。我嘗試了下面的代碼進行測試,但是這個覆蓋被調用了兩次。js覆蓋函數被調用兩次

Date.prototype.getFullYear = (function(){ 
    var $gfy = Date.prototype.getFullYear; 
    if (!this.done) { 
     this.done = true; // add my own variable to this instance 
     return function() { 
      return $gfy.call(this)+150; 
     }; 
    } else { 
     return function() { 
      return $gfy.call(this); 
     }; 
    } 
}()); 

所以,

  1. 什麼是覆蓋本機的功能我怎麼一個變量添加到原始實例的正確方法和

  2. 如何獲得實例本身(這在這裏不起作用)。

回答

1

一些重要的區別首先(您可能已經知道這一點,但只是讓我們在同一頁面上)。

prototype更改所有對象(實例和未來實例)的行爲。因此,在修改內置類型(日期,字符串等)時,請謹慎行事,因爲您將爲使用它們的每個例程更改這些對象的行爲。

Live Demo

//Add a property to the instance 
var date = new Date(); 
date.newProp = 'test'; 
alert(date.newProp); //test 

//----VS---- 

//Add a property to all instances existing 
//and too be created 
Date.prototype.newProp2 = 'new prop'; 

var date2 = new Date(); 
alert(date2.newProp);//undefined 
alert(date2.newProp2); //new prop 

//See how the prototype modified the existing instance as well. 
alert(date.newProp2); //new prop 

爲了回答您的具體問題:

  1. 它看起來像您正確overridding本機的功能。存儲本機功能的副本,以便您可以將它稱爲base功能。
  2. 從我上面的示例中,您將需要修改所有Date實例或僅修改所討論的實例。
    • var date = new Date(); date.done = false;
    • Date.prototype.done = false;
  3. 原因this不會在外部函數的工作是因爲它是一個self executing anonymous function,並以分配的你的內在功能之一到getFullYear方法立即執行。

總而言之,由於存在干擾其他庫的危險,我不確定你的方法是最好的主意,我不確定爲什麼你只希望這個函數返回+150時間每個日期實例,但這裏是您的代碼修改,以執行您的預期邏輯。

Live Demo

//Add a variable to all Date objects 
Date.prototype.done = false; 

//Override the getFullYear function 
Date.prototype.getFullYear = (function(){ 

    //Store a reference to the native function 
    var $gfy = Date.prototype.getFullYear; 
    return function(){ 

     //Have we hit this routine before? 
     if (!this.done) { 

      //We've hit this routine once so flag it. 
      this.done = true; 

      //Execute native funciton, then add 150 
      return $gfy.call(this)+150; 
     } else { 

      //Call the native function from now on. 
      return $gfy.call(this); 
     } 
    } 
}());//self executing function so it executes as soon as it is evaluated. 

var date = new Date(); 

//Will return +150 the first time 
alert(date.getFullYear()); 

//After that execute the default 
//function for'getFullYear' 
alert(date.getFullYear()); 
+0

感謝交代。根據你的陳述,'this'指的是函數,而我想要得到那個實例(用'new'來完成)。用戶可以用不同的初始日期實例化許多日期類。 注:我的意圖是根據實例的年份(而不是+150)進行進一步計算。 – alsaleem