一些重要的區別首先(您可能已經知道這一點,但只是讓我們在同一頁面上)。
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
爲了回答您的具體問題:
- 它看起來像您正確overridding本機的功能。存儲本機功能的副本,以便您可以將它稱爲
base
功能。
- 從我上面的示例中,您將需要修改所有Date實例或僅修改所討論的實例。
var date = new Date(); date.done = false;
Date.prototype.done = false;
- 原因
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());
感謝交代。根據你的陳述,'this'指的是函數,而我想要得到那個實例(用'new'來完成)。用戶可以用不同的初始日期實例化許多日期類。 注:我的意圖是根據實例的年份(而不是+150)進行進一步計算。 – alsaleem