2012-05-08 38 views
2

我正在用几个'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创建别名的目的)

回答

2

正如其他人所说,你可以使用callapply(或者将工作,所不同的仅仅是如何将参数传递给函数) 。

或者,你可以使用ES5 bind方法,结合上下文的功能(在这种情况下,背景会this):

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

然后,您可以拨打shortName像通常那样:

shortName(); 

这是working example。而这里的MDN文章的最相关的部分:

的bind()函数创建一个新的功能(绑定功能)与 相同的函数体(在ECMAScript中5项内部调用属性)作为 功能它被绑定到bind(), 的第一个参数,它不能被覆盖,这个值被调用(绑定函数的目标 函数)。

+0

谢谢。这可能是答案,我只需要评估我的代码和本文中描述的部分实现是否可以在IE8 –

+0

中工作@MarkBrown - MDN文章中描述的垫片应该可以做到。或者,查看[ES5 shim](https://github.com/kriskowal/es5-shim/),但如果这是您需要的唯一ES5功能,则可能会过大。 –

0

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

这是javascript是一个小窍门。基于上下文。

+0

感谢。请参阅我的编辑,我宁愿一个解决方案,不需要更改我称为shortName() –

1

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

shortName.apply(this); 

OR

shortName.call(this); 
+0

谢谢。请参阅我的编辑,我更喜欢不需要改变我称为shortName() –

+0

的解决方案如果您的意图是提供较长的函数名称,那么如何使用[module pattern](http: //www.klauskomenda。com/code/javascript-programming-patterns /#module)或[揭示模块模式](http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing),甚至是[揭示原型模式] (http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx)? –