我正在用几个'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功能,则可能会过大。 –