2

我正在构建一个包含多个“模块”的应用程序。每个模块都需要一组类似的基本功能,因此我创建了一个基本模块,每个模块都将通过原型继承从该基本模块中继承。基本模块上的一些函数名称很长,并且由于这些函数经常使用,我想在每个模块中分配较短的名称,但这会导致将“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 创建别名的目的)

4

4 回答 4

2

正如其他人所提到的,您可以使用callor apply(两者都可以,区别只是参数如何传递给函数)。

或者,您可以使用 ES5bind方法,该方法将上下文绑定到函数(在这种情况下,上下文将为this):

var shortName = this.someLongFunctionName.bind(this);

shortName然后,您可以像往常一样调用:

shortName();

这是一个工作示例。这是 MDN 文章中最相关的部分:

bind() 函数创建一个新函数(绑定函数),其函数主体(ECMAScript 5 术语中的内部 Call 属性)与正在调用它的函数(绑定函数的目标函数)相同,并且 this 值绑定到bind() 的第一个参数,不能被覆盖。

于 2012-05-08T17:52:30.157 回答
1

您可以使用 call / apply 函数将“this”上下文传递给方法调用。在您的情况下,它可以是

shortName.apply(this);

或者

shortName.call(this);
于 2012-05-08T17:50:06.703 回答
1

另一种解决方案是使用绑定函数将新上下文绑定到函数。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

var shortName = this.someLongFunctionName.bind(this);
于 2012-05-08T17:53:40.697 回答
0

您可以将呼叫更改shortName();shortName.call(this);

这是javascript有点技巧。是基于上下文的。

于 2012-05-08T17:50:00.527 回答