我正在构建一个包含多个“模块”的应用。每个模块都需要类似的基本功能集,因此我创建了一个基本模块,每个模块都将通过原型继承继承。基本模块上的一些函数名称很长,并且由于经常使用这些函数,我想在每个模块中分配较短的名称,但这会导致'this'设置值等于DOMWindow的问题。
请参阅以下代码:
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),这样就失去了为someLongFunctionName创建别名的目的)
答案 0 :(得分:2)
正如其他人所提到的,您可以使用call
或apply
(两者都可以使用,区别在于参数是如何传递给函数的。)
或者,您可以使用ES5 bind
方法,该方法将上下文绑定到函数(在本例中,上下文将为this
):
var shortName = this.someLongFunctionName.bind(this);
然后您可以像往常一样致电shortName
:
shortName();
这是一个working example。这是MDN文章中最相关的部分:
bind()函数用。创建一个新函数(一个绑定函数) 相同的函数体(ECMAScript 5术语中的内部Call属性)as 它被调用的函数(绑定函数的目标 函数)将此值绑定到bind()的第一个参数, 这是不能被覆盖的。
答案 1 :(得分:1)
您可以使用call / apply函数将“this”上下文传递给方法调用。在你的情况下,它可以是
shortName.apply(this);
OR
shortName.call(this);
答案 2 :(得分:1)
另一种解决方案是使用绑定函数将新上下文绑定到函数。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
var shortName = this.someLongFunctionName.bind(this);
答案 3 :(得分:0)
您可以将通话更改为shortName();
至shortName.call(this);
。
这是javascript有点戏法。基于上下文。