我正在用幾個'modules'構建一個應用程序。每個模塊都需要一組類似的基本功能,所以我創建了一個基本模塊,每個模塊都將通過原型繼承繼承。基本模塊上的某些函數名稱相當長,而且由於這些函數經常使用,所以我想在每個模塊中分配較短的名稱,但這會導致'this'的值設置爲等於DOMWindow。原型繼承和'this'的值
請參閱下面的代碼:
var SAMPLEAPP = SAMPLEAPP || {};
//This is a base module that I want all other modules to inherit from
SAMPLEAPP.Module = function(){
};
SAMPLEAPP.Module.prototype.someLongFunctionName = function(){
console.log(this);
};
//This is a module that inherits from the base module
SAMPLEAPP.RouterModule= function(){
var shortName = this.someLongFunctionName;
//This correctly logs 'SAMPLEAPP.RouterModule', but I would rather not type
//out this long function name each time I need to use the function
this.someLongFunctionName();
//However, this code logs 'DOMWindow' when I would expect the value of 'this'
//to be the same as the direct call to this.someLongFunctionName
shortName();
};
SAMPLEAPP.RouterModule.prototype = new SAMPLEAPP.Module();
new SAMPLEAPP.RouterModule();
我的問題:我如何可以修改代碼,以便調用SHORTNAME()記錄SAMPLEAPP.RouterModule?如果可能的話,我寧願改變定義模塊的方式,而不是實際調用shortName(即shortname.call(this),這會破壞爲某些LongFunctionName創建別名的目的)
謝謝。這可能是答案,我只需要評估我的代碼和本文中描述的部分實現是否可以在IE8 –
中工作@MarkBrown - MDN文章中描述的墊片應該可以做到。或者,查看[ES5 shim](https://github.com/kriskowal/es5-shim/),但如果這是您需要的唯一ES5功能,則可能會過大。 –